package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.base.auth.context.LoginContextHolder;
import cn.stylefeng.guns.base.auth.model.LoginUser;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.core.exception.BusException;
import cn.stylefeng.guns.sys.core.exception.enums.BizExceptionEnum;
import cn.stylefeng.guns.sys.core.exception.enums.BusExceptionEnum;
import cn.stylefeng.guns.sys.core.properties.GzhConfig;
import cn.stylefeng.guns.sys.core.properties.SysConfig;
import cn.stylefeng.guns.sys.core.util.DateUtil;
import cn.stylefeng.guns.sys.core.util.ExcelFormatUtil;
import cn.stylefeng.guns.sys.core.util.PageUtil;
import cn.stylefeng.guns.sys.core.util.UUIDUtils;
import cn.stylefeng.guns.sys.modular.system.controller.BaseFrontController;
import cn.stylefeng.guns.sys.modular.system.db4.service.TeamService;
import cn.stylefeng.guns.sys.modular.system.entity.*;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.ProjectTaskEnum;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.RoleIdEnum;
import cn.stylefeng.guns.sys.modular.system.entity.Enum.UseEnum;
import cn.stylefeng.guns.sys.modular.system.mapper.*;
import cn.stylefeng.guns.sys.modular.system.model.params.*;
import cn.stylefeng.guns.sys.modular.system.model.result.*;
import cn.stylefeng.guns.sys.modular.system.service.*;
import cn.stylefeng.roses.core.reqres.response.ResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.streaming.SXSSFCell;
import org.apache.poi.xssf.streaming.SXSSFRow;
import org.apache.poi.xssf.streaming.SXSSFSheet;
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.ParseException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiangge
 * @since 2020-09-10
 */
@Service
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements ProjectService {

    private static final Logger log = LoggerFactory.getLogger(ProjectServiceImpl.class);
    @Autowired
    private TaskFlowService taskFlowService;
    @Autowired
    private TaskStatusService taskStatusService;
    @Resource
    private TaskService taskService;
    @Resource
    private WeChatSendTempMsgService weChatSendTempMsgService;
    @Resource
    private SysConfig sysConfig;
    @Resource
    private BtyArchivesMapper btyArchivesMapper;
    @Resource
    private ProjectMapper projectMapper;
    @Resource
    private MouldBoardMsgMapper mouldBoardMsgMapper;
    @Resource
    private UserService userService;
    @Resource
    private TaskMapper taskMapper;
    @Resource
    private TaskFlowMapper taskFlowMapper;
    @Resource
    private BtyWxService btyWxService;
    @Resource
    private MdzxMapper mdzxMapper;
    @Resource
    private BtyWxMapper btyWxMapper;
    @Resource
    private GcgMsgMapper msgMapper;
    @Resource
    private ProjectService projectService;
    @Resource
    private GzhConfig gzhConfig;
    private TaskStatusMapper statusMapper;
    @Resource
    private WxmsgPushService wxmsgPushService;
    @Resource
    private UserMapper userMapper;
    @Resource
    private AreaService areaService;
    @Autowired
    private TeamService teamService;
    @Autowired
    private BtyTxlMapper btyTxlMapper;
    @Autowired
    private PushMsgService pushMsgService;
    @Autowired
    private BtyBrandMapper btyBrandMapper;
    @Autowired
    private BtyWmtxlMapper btyWmtxlMapper;
    @Autowired
    private BtyWmtxlService btyWmtxlService;
    @Resource
    private BtyContractMapper btyContractMapper;
    @Resource
    private BtyDoubleCardMapper doubleCardMapper;

    // 跳转URL
    private String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=";
//    private String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx373650bf8de7f27d&redirect_uri=";
//    private String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx0215c6330cc918bf&redirect_uri=";
    private String type = "&response_type=code";
    private String scope = "&scope=snsapi_userinfo";
    private String state = "&state=STATE#wechat_redirect";


    private final int enable = 1;
    private final int disable = 0;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void add(ProjectParam param) {
        //拼接工程名称
        param.setStatus(BusConst.PASS);
//        param.setName(new StringBuilder(param.getProvinceName()).append(param.getCityName()).append(param.getName()).toString());
        param.setCreateUser(LoginContextHolder.getContext().getUserId());
        Project entity = getEntity(param);
        if(ToolUtil.isNotEmpty(param.getTel())){
            entity.setYyjl(param.getTel());
        }
        this.save(entity);

        //更新 taskFlow
        TaskFlowParam taskFlowParam = new TaskFlowParam();
        taskFlowParam.setProId(entity.getId());
        //创建店名对应的taskId   1-店名
        taskFlowParam.setTaskId(ProjectTaskEnum.TASK_1.getCode());
        //1提交；2审核未通过；3审核通过
        taskFlowParam.setStatus(1);
        taskFlowParam.setTaskName(ProjectTaskEnum.TASK_1.getMessage());
        taskFlowService.add(taskFlowParam);

        //更新 taskStatus
        TaskStatusParam taskStatusParam = new TaskStatusParam();
        taskStatusParam.setProId(entity.getId());
        //创建店名对应的taskId   1-店名
        taskStatusParam.setTaskId(ProjectTaskEnum.TASK_1.getCode());

        //1提交；2审核未通过；3审核通过
        taskStatusParam.setStatus(1);
        taskStatusService.add(taskStatusParam);

        //开发人员指定营运经理
        if(ToolUtil.isNotEmpty(param.getTel())){
            TaskStatusParam statusParam = new TaskStatusParam();
            //创建开发人员指定营运经理对应的taskId  61
            statusParam.setTaskId(ProjectTaskEnum.TASK_61.getCode());
            statusParam.setProId(entity.getId());
            //创建店名对应的taskId   1-店名
            //1提交；2审核未通过；3审核通过
            statusParam.setStatus(1);
            taskStatusService.add(statusParam);

            TaskFlowParam flowParam = new TaskFlowParam();
            flowParam.setProId(entity.getId());
            //创建开发人员指定营运经理对应的taskId  61
            flowParam.setTaskId(ProjectTaskEnum.TASK_61.getCode());
            //1提交；2审核未通过；3审核通过
            flowParam.setStatus(1);
            flowParam.setTaskName(ProjectTaskEnum.TASK_61.getMessage());
            taskFlowService.add(flowParam);
        }

        taskStatusService.insertNextNode(taskStatusParam);//插入下个节点
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addH5(ProjectParam param,Long userId) {
        //拼接工程名称
        param.setStatus(BusConst.PASS);
        param.setCreateUser(userId);
        Project entity = getEntity(param);
        this.save(entity);

        //更新 taskFlow
        TaskFlowParam taskFlowParam = new TaskFlowParam();
        taskFlowParam.setProId(entity.getId());
        //创建店名对应的taskId   1-店名
        taskFlowParam.setTaskId(ProjectTaskEnum.TASK_1.getCode());
        //1提交；2审核未通过；3审核通过
        taskFlowParam.setStatus(1);
        taskFlowParam.setTaskName(ProjectTaskEnum.TASK_1.getMessage());
        taskFlowService.addH5(taskFlowParam,userId);

        //更新 taskStatus
        TaskStatusParam taskStatusParam = new TaskStatusParam();
        taskStatusParam.setProId(entity.getId());
        //创建店名对应的taskId   1-店名
        taskStatusParam.setTaskId(ProjectTaskEnum.TASK_1.getCode());
        //1提交；2审核未通过；3审核通过
        taskStatusParam.setStatus(1);
        taskStatusService.addH5(taskStatusParam,userId);

        taskStatusService.insertNextNodeH5(taskStatusParam,userId);//插入下个节点
    }

    @Override
    public void delete(ProjectParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(ProjectParam param) {
        Project oldEntity = getOldEntity(param);
        Project newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        newEntity.setUpdateUser(LoginContextHolder.getContext().getUserId());

        this.updateById(newEntity);
    }

    @Override
    public ProjectResult findBySpec(ProjectParam param) {
        return null;
    }

    @Override
    public List<ProjectResult> findListBySpec(ProjectParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(ProjectParam param) throws ParseException {

        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        List<Long> roleList = currentUser.getRoleList();
        List<Integer> taskByRole = taskStatusService.getTaskByRole(roleList);
        param.setTaskids(StringUtils.join(taskByRole,","));
        User curtuser = userService.getById(currentUser.getId());
        String phone = curtuser.getPhone();
        String jiedian=param.getJiedian();

        Page pageContext = getPageContext();
        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
        Long role_kfqyjl = RoleIdEnum.ROLE_KFQYJL.getCode();//开发区域经理
        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
        Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();//开发人员
        Long role_yyjl = RoleIdEnum.ROLE_YYJL.getCode();//营运经理
        Long role_dd = RoleIdEnum.ROLE_DD.getCode();//督导
        Long role_netshop = RoleIdEnum.ROLE_NETSHOP.getCode();//网上建店负责人
        Long role_gcb = RoleIdEnum.ROLE_GCB.getCode();//工程部
        if (roleList.contains(role_kfry)) {
            param.setCreateUser(currentUser.getId());
        }
        if (roleList.contains(role_yyjl)) {
            param.setYyjl(phone);
        }
        if (roleList.contains(role_kfqyjl)) {
            param.setKfqyjl(phone);
            param.setCreateUser(currentUser.getId());
        }
        if (roleList.contains(role_dd)) {
            param.setDd(phone);
        }
        if(ToolUtil.isNotEmpty(jiedian)){
            param.setJiedian(jiedian);
        }
        IPage page = this.baseMapper.customPageList(pageContext, param);
        taskService.setProcessSteps(page.getRecords());
        List<ProjectResult> records = page.getRecords();

        List<TaskResult> listIds = taskService.listIdsByRoleIds(String.join(",", role_kfry.toString(), role_gczj.toString(), role_kfzj.toString()));
        Map<Long, String> roleIdTaskIds = listIds.stream().collect(Collectors.toMap(TaskResult::getRoleId, TaskResult::getIds));
        //获取开发人员任务完成情况
        String kf_taskids = roleIdTaskIds.get(role_kfry);
        String gczj_taskids = roleIdTaskIds.get(role_gczj);
        String kfzj_taskids = roleIdTaskIds.get(role_kfzj);

        //所有taskStatus信息
        List<TaskStatus> taskStatusList = taskStatusService.listTaskStatus();
        Map<Integer, List<TaskStatus>> taskStatusProIdMap = taskStatusList.stream().collect(Collectors.groupingBy(TaskStatus::getProId));
        List<TaskStatus> rejects = taskStatusService.listReject();
        Map<String, TaskStatus> rejectMap = rejects.stream().collect(Collectors.toMap(k -> k.getProId() + "_" + k.getTaskId(), Function.identity()));
        Date curtDate = new Date();
        List<Map> maps = teamService.selectYyjlList();
        Map<Object, Object> yyjlmap = maps.stream().collect(Collectors.toMap(s -> s.get("tel"), s -> s.get("yyjl")));
        List<Map> maps2 = teamService.selectDdListAll();
        Map<Object, Object> ddmap = maps2.stream().collect(Collectors.toMap(s -> s.get("tel"), s -> s.get("dd")));
        Iterator<ProjectResult> iterator = records.iterator();
        while (iterator.hasNext()) {
            ProjectResult rs = iterator.next();
            Integer proid = rs.getId();

            //根据角色获取任务ids
            boolean kfry_ts = isexist2(taskStatusProIdMap.get(proid), kf_taskids);
            //获取工程总监任务完成情况
            boolean gczj_ts = isexist2(taskStatusProIdMap.get(proid), gczj_taskids);
            //获取开发总监任务完成情况
            boolean kfzj_ts = isexist2(taskStatusProIdMap.get(proid), kfzj_taskids);
            //获取营运总监审核
            boolean yyzj_ts = isexist2(taskStatusProIdMap.get(proid), "7");
            if (yyzj_ts) {//yyzj已确认
                //是否确认开工日期
                rs.setKgtime("开工日期未确定");
                String kaigong = "32";
//                boolean kaigong_ts = isexist(proid, kaigong);
                List<TaskStatus> listts = this.getTaskStatusListByTaskIds(taskStatusProIdMap.get(proid), kaigong);
                rs.setGckg(enable);
                if (ToolUtil.isNotEmpty(listts)) {
                    long num = DateUtil.getDaysNum(listts.get(0).getContent(), DateUtil.getNowDate());
                    if (num < 0) {
                        rs.setKgtime("开工日期：" + listts.get(0).getContent());
                    } else {
                        //判断工程是否完成
                        List<TaskStatus> list=getTaskStatusListByTaskIds(taskStatusProIdMap.get(proid),"34");
                        if(list.size()>0){
                            String finiDate = list.get(0).getContent();
                            if (ToolUtil.isNotEmpty(finiDate)) {
                                Date finDate = DateUtil.getDateByStr(finiDate);
                                if(finDate.before(curtDate)){
                                    rs.setKgtime("已完工");
                                }else{
                                    rs.setKgtime("已开工" + num + "天");
                                }
                            } else {
                                rs.setKgtime("");
                            }
                        }else{
                            rs.setKgtime("已开工" + num + "天");
                        }
                    }
                }
                if (roleList.contains(role_yyzj)) {//营运总监
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    rs.setSelectyyjl(enable);

                    if (ToolUtil.isNotEmpty(rs.getYyjl())) {
                        /*Map<String, Object> map = new HashMap<>();
                        map.put("tel", rs.getYyjl());
                        BtyArchives arch = btyArchivesMapper.getObjByCon(map);
                        if (arch != null) {
                            rs.setYyjlname(arch.getXm());
                        } else {
                            rs.setYyjlname("无名");
                        }*/
                        rs.setYyjlname(String.valueOf(yyjlmap.get(rs.getYyjl())==null?"无名":yyjlmap.get(rs.getYyjl())));
                    }
                    if (ToolUtil.isNotEmpty(listts) && ToolUtil.isNotEmpty(rs.getDd())) {
                        rs.setKdtask(enable);//开店任务
                    }
                }
                if (roleList.contains(role_yyjl)) {//营运经理
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    rs.setSelectdd(enable);
                    if (ToolUtil.isNotEmpty(rs.getDd())) {
                        /*Map<String, Object> map = new HashMap<>();
                        map.put("tel", rs.getDd());
                        BtyArchives arch = btyArchivesMapper.getObjByCon(map);
                        if (arch != null) {
                            rs.setDdname(arch.getXm());
                        } else {
                            rs.setDdname("无名");
                        }*/
                        rs.setDdname(String.valueOf(ddmap.get(rs.getDd())==null?"无名":ddmap.get(rs.getDd())));
                    }
                    if (ToolUtil.isNotEmpty(listts) && ToolUtil.isNotEmpty(rs.getDd())) {
                        rs.setKdtask(enable);//开店任务
                    }
                }
                if (roleList.contains(role_dd)) {//督导
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    if (ToolUtil.isNotEmpty(listts) && ToolUtil.isNotEmpty(phone) && phone.equals(rs.getDd())) {
                        rs.setKdtask(enable);//开店任务
                        rs.setKdtaskedit(enable);//开店任务信息可否编辑
                    }
                }
                if (roleList.contains(role_kfry)) {//工程开发人员、
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                }
                if (roleList.contains(role_gczj)) {//工程总监
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                }

               if (roleList.contains(role_gcb)) {//工程部
                    rs.setGcbtn(enable);
                    rs.setGckgedit(enable);
                }
                if (roleList.contains(role_netshop)) {//网上建店负责人
                    if (ToolUtil.isNotEmpty(listts)) {
                        rs.setKdtask(enable);//开店任务
//                        rs.setKdtaskedit(enable);//开店任务信息可否编辑
                    }
                    //如果督导三个表格已完成，才能建店
                    Integer addrMouldid = 34;
                    Integer mealMouldid = 35;
                    Integer queuMouldid = 37;
                    List<MouldBoardMsg> addrlist = mouldBoardMsgMapper.getRecordByMould(addrMouldid);
                    List<MouldBoardMsg> meallist = mouldBoardMsgMapper.getRecordByMould(mealMouldid);
                    List<MouldBoardMsg> queuelist = mouldBoardMsgMapper.getRecordByMould(queuMouldid);
                    if (addrlist.size() > 0) {
                        //网上建店按钮
                        rs.setNetshopAddr(enable);
                    }
                    if (meallist.size() > 0) {
                        //线上套餐按钮
                        rs.setMealOnline(enable);
                    }
                    if (queuelist.size() > 0) {
                        //排队机按钮
                        rs.setQueueMachine(enable);
                    }
                }
                if (roleList.contains(role_kfzj)) {//开发总监
                    //商务条件按钮
                    rs.setSwbtn(enable);
                    //工程条件按钮
                    rs.setGcbtn(enable);
                }
                if (roleList.contains(role_kfqyjl)) {//开发区域经理
                    //商务条件按钮
                    rs.setSwbtn(enable);
                    //工程条件按钮
                    rs.setGcbtn(enable);
                }

            } else if (gczj_ts && kfzj_ts) {//kfzj+gczj OK
                if (roleList.contains(role_gczj) || roleList.contains(role_kfry)) {//工程总监/开发人员
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                } else if (roleList.contains(role_yyzj)) {//营运总监
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    boolean isexist = isexist2(taskStatusProIdMap.get(proid), "7");//营运总监确认taskid
                    if (!isexist) {
                        //商务条件审核按钮
                        rs.setAuditbtn(enable);
                    }
                } else if (roleList.contains(role_kfzj)) {//开发总监
                    rs.setSwbtn(enable);
                    rs.setGcbtn(enable);
                }
                else if (roleList.contains(role_kfqyjl)) {//开发区域经理
                    rs.setSwbtn(enable);
                    rs.setGcbtn(enable);
                }
            } else if (kfry_ts) {//开发人员任务完成
                if (roleList.contains(role_gczj)) {//工程总监
                    boolean isexist0 = isexist2(taskStatusProIdMap.get(proid), "6");//开发总监确认
                    if(isexist0){
                        rs.setSwbtn(enable);
                    }else{
                        rs.setSwbtn(2);
                    }
                    rs.setGcbtn(enable);
                    boolean isexist = isexist2(taskStatusProIdMap.get(proid), "5");//工程总监确认taskid
                    if (!isexist) {
                        //商务条件通过驳回按钮是否显示
                        rs.setAuditbtn(disable);
                        //工程条件通过驳回按钮是否显示
                        rs.setAuditbtn1(enable);
                    }
                } else if (roleList.contains(role_kfqyjl)) {//开发区域经理
                    rs.setSwbtn(enable);
                    rs.setGcbtn(enable);
                    boolean isexist = isexist2(taskStatusProIdMap.get(proid), "62");//开发区域经理确认taskid
                    if (!isexist) {
                        //商务条件通过驳回按钮是否显示
                        rs.setAuditbtn(enable);
                        //工程条件通过驳回按钮是否显示
                        rs.setAuditbtn1(disable);
                    }
                }else if (roleList.contains(role_kfzj)) {//开发总监
                    rs.setSwbtn(enable);
                    rs.setGcbtn(enable);
                    boolean isexist = isexist2(taskStatusProIdMap.get(proid), "6");//开发总监确认taskid
                    if (!isexist) {
                        //商务条件通过驳回按钮是否显示
                        rs.setAuditbtn(enable);
                        //工程条件通过驳回按钮是否显示
                        rs.setAuditbtn1(disable);
                    }
                }
                else if (roleList.contains(role_kfry)) {//开发人员
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                } else if (roleList.contains(role_yyzj)) {//营运总监
                    rs.setSwbtn(enable);
                    rs.setGcbtn(enable);
                }
            } else {//kf人员未完成
                boolean swisexist = isexist2(taskStatusProIdMap.get(proid), "3");//sw
                boolean gcisexist = isexist2(taskStatusProIdMap.get(proid), "2");//gc

                if (roleList.contains(role_kfry)&&roleList.contains(role_kfqyjl)) {//开发人员//开发区域经理
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    if (!swisexist) {
                        //商务模板条件可否编辑
                        rs.setSwedit(enable);
                    }
                    if (!gcisexist) {
                        //工程模板条件可否编辑
                        rs.setGcedit(enable);
                    }

                    if (swisexist) {//店名和商务条件完成
                        rs.setSwbtn(enable);
                        boolean isexist = isexist2(taskStatusProIdMap.get(proid), "62");//开发区域经理确认taskid
                        if (!isexist) {
                            //商务条件通过驳回按钮是否显示
                            rs.setAuditbtn(enable);
                            //工程条件通过驳回按钮是否显示
                            rs.setAuditbtn1(disable);
                        }
                    }
                }
               else if (roleList.contains(role_kfry)) {//开发人员
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    if (!swisexist) {
                        //商务模板条件可否编辑
                        rs.setSwedit(enable);
                    }
                    if (!gcisexist) {
                        //工程模板条件可否编辑
                        rs.setGcedit(enable);
                    }

                }

               else if (roleList.contains(role_kfqyjl)) {//开发区域经理
                    if (swisexist) {//店名和商务条件完成
                        rs.setSwbtn(enable);
                        boolean isexist = isexist2(taskStatusProIdMap.get(proid), "62");//开发区域经理确认taskid
                        if (!isexist) {
                            //商务条件通过驳回按钮是否显示
                            rs.setAuditbtn(enable);
                            //工程条件通过驳回按钮是否显示
                            rs.setAuditbtn1(disable);
                        }
                    }
                }


                else if (roleList.contains(role_kfzj)) {//开发总监
                    if (swisexist) {//店名和商务条件完成
                        rs.setSwbtn(enable);
                        boolean isexist = isexist2(taskStatusProIdMap.get(proid), "6");//开发总监确认taskid
                        if (!isexist) {
                            //商务条件通过驳回按钮是否显示
                            rs.setAuditbtn(enable);
                        }
                    }
                    if (gcisexist) {
                        rs.setGcbtn(enable);
                    }
                } else if (roleList.contains(role_yyzj)) {//营运总监
                    if (swisexist) {
                        rs.setSwbtn(enable);
                    }
                    if (gcisexist) {
                        rs.setGcbtn(enable);
                    }
                }
                if(ToolUtil.isNotEmpty(rs.getKfzj()) && rs.getKfzj().contains("驳回")){
                    rs.setSwbtn(-1);
                    TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_6.getCode());
                    rs.setRejectInfo("开发总监'"+rej.getCreateName()+"'已驳回,原因："+rej.getContent());
                }
                if(ToolUtil.isNotEmpty(rs.getKfqyjl()) && rs.getKfqyjl().contains("驳回")){
                    rs.setSwbtn(-1);
                    TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_62.getCode());
                    rs.setRejectInfo("开发区域经理'"+rej.getCreateName()+"'已驳回,原因："+rej.getContent());
                }
                if(ToolUtil.isNotEmpty(rs.getGczj()) && rs.getGczj().contains("驳回")){
                    rs.setGcbtn(-1);
                    TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_5.getCode());
                    rs.setRejectInfo("工程总监'"+rej.getCreateName()+"'已驳回,原因："+rej.getContent());
                }
                if(ToolUtil.isNotEmpty(rs.getYyzj()) && rs.getYyzj().contains("驳回")){
                    rs.setGcbtn(-1);
                    TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_7.getCode());
                    rs.setRejectInfo("营运总监'"+rej.getCreateName()+"'已驳回,原因："+rej.getContent());
                }
            }

        }
        System.out.println("page:"+page);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public LayuiPageInfo adminList(ProjectParam param) throws ParseException {
        LoginUser currentUser = LoginContextHolder.getContext().getUser();
        List<Long> roleList = currentUser.getRoleList();
        User curtuser = userService.getById(currentUser.getId());
        String phone = curtuser.getPhone();
        Page pageContext = getPageContext();
        /*Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
        Long _ = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
        Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();//开发人员
        Long role_yyjl = RoleIdEnum.ROLE_YYJL.getCode();//营运经理
        Long role_dd = RoleIdEnum.ROLE_DD.getCode();//督导
        Long role_netshop = RoleIdEnum.ROLE_NETSHOP.getCode();//网上建店负责人
        Long role_gcb = RoleIdEnum.ROLE_GCB.getCode();//工程部
        if (roleList.contains(role_kfry)) {
            param.setCreateUser(currentUser.getId());
        }
        if (roleList.contains(role_yyjl)) {
            param.setYyjl(phone);
        }
        if (roleList.contains(role_dd)) {
            param.setDd(phone);
        }*/
        IPage page = this.baseMapper.customPageListAdmin(pageContext, param);
       List<ProjectResult> records = page.getRecords();
        taskService.setProcessSteps(page.getRecords());
         /*List<TaskResult> listIds = taskService.listIdsByRoleIds(String.join(",", role_kfry.toString(), role_gczj.toString(), role_kfzj.toString()));
        Map<Long, String> roleIdTaskIds = listIds.stream().collect(Collectors.toMap(TaskResult::getRoleId, TaskResult::getIds));
        //获取开发人员任务完成情况
        String kf_taskids = roleIdTaskIds.get(role_kfry);
        String gczj_taskids = roleIdTaskIds.get(role_gczj);
        String kfzj_taskids = roleIdTaskIds.get(role_kfzj);*/

        //所有taskStatus信息
        List<TaskStatus> taskStatusList = taskStatusService.listTaskStatus();
        Map<Integer, List<TaskStatus>> taskStatusProIdMap = taskStatusList.stream().collect(Collectors.groupingBy(TaskStatus::getProId));
        List<TaskStatus> rejects = taskStatusService.listReject();
        Map<String, TaskStatus> rejectMap = rejects.stream().collect(Collectors.toMap(k -> k.getProId() + "_" + k.getTaskId(), Function.identity()));

//        List<Integer> yyzj_t = taskService.listIdsByRole(role_yyzj);
//        String yyzj_taskids=StringUtils.join(yyzj_t.toArray(), ",");
        List<Map> maps = teamService.selectYyjlList();
        Map<Object, Object> yyjlmap = maps.stream().collect(Collectors.toMap(s -> s.get("tel"), s -> s.get("yyjl")));
        List<Map> maps2 = teamService.selectDdListAll();
        Map<Object, Object> ddmap = maps2.stream().collect(Collectors.toMap(s -> s.get("tel"), s -> s.get("dd")));
        Iterator<ProjectResult> iterator = records.iterator();
        while (iterator.hasNext()) {
            ProjectResult rs = iterator.next();
            Integer proid = rs.getId();

            rs.setGcbtn(enable);
            rs.setGcedit(enable);
            rs.setSwbtn(enable);
            rs.setSwedit(enable);
            rs.setKdtask(enable);
            rs.setKdtaskedit(enable);
            rs.setGckg(enable);
            rs.setGckgedit(enable);

            rs.setSelectyyjl(enable);
            rs.setSelectdd(enable);
            rs.setNetshopAddr(enable);
            rs.setQueueMachine(enable);
            rs.setMealOnline(enable);
            rs.setAuditbtn(enable);

            //获取营运总监审核
            boolean yyzj_ts = isexist2(taskStatusProIdMap.get(proid), "7");
            //根据角色获取任务ids--kfry
            boolean kfry_ts = isexist2(taskStatusProIdMap.get(proid), "1,2,3");
            if (yyzj_ts) {//yyzj已确认
                //是否确认开工日期
                rs.setKgtime("开工日期未确定");
                String kaigong = "32";
                List<TaskStatus> listts = this.getTaskStatusListByTaskIds(taskStatusProIdMap.get(proid), kaigong);
                if (ToolUtil.isNotEmpty(listts)) {
                    long num = DateUtil.getDaysNum(listts.get(0).getContent(), DateUtil.getNowDate());
                    if (num < 0) {
                        rs.setKgtime("开工日期：" + listts.get(0).getContent());
                    } else {
                        rs.setKgtime("已开工" + num + "天");
                    }
                }
                if (ToolUtil.isNotEmpty(rs.getYyjl())) {
                    /*Map<String, Object> map = new HashMap<>();
                    map.put("tel", rs.getYyjl());
                    BtyArchives arch = btyArchivesMapper.getObjByCon(map);
                    if (arch != null) {
                        rs.setYyjlname(arch.getXm());
                    } else {
                        rs.setYyjlname("无名");
                    }*/
                    rs.setYyjlname(String.valueOf(yyjlmap.get(rs.getYyjl())==null?"无名":yyjlmap.get(rs.getYyjl())));
                }
                if (ToolUtil.isNotEmpty(rs.getDd())) {
                   /* Map<String, Object> map = new HashMap<>();
                    map.put("tel", rs.getDd());
                    BtyArchives arch = btyArchivesMapper.getObjByCon(map);
                    if (arch != null) {
                        rs.setDdname(arch.getXm());
                    } else {
                        rs.setDdname("无名");
                    }*/
                    rs.setDdname(String.valueOf(ddmap.get(rs.getDd())==null?"无名":ddmap.get(rs.getDd())));
                }
            }else if(!kfry_ts){
                if(ToolUtil.isNotEmpty(rs.getKfzj()) && rs.getKfzj().contains("驳回")){
                    rs.setSwbtn(-1);
                    TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_6.getCode());
                    rs.setRejectInfo("开发总监'"+rej.getCreateName()+"'已驳回,原因："+rej.getContent());
                }
                if(ToolUtil.isNotEmpty(rs.getGczj()) && rs.getGczj().contains("驳回")){
                    rs.setGcbtn(-1);
                    TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_5.getCode());
                    rs.setRejectInfo("工程总监'"+rej.getCreateName()+"'已驳回,原因："+rej.getContent());
                }
                if(ToolUtil.isNotEmpty(rs.getYyzj()) && rs.getYyzj().contains("驳回")){
                    rs.setGcbtn(-1);
                    TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_7.getCode());
                    rs.setRejectInfo("营运总监'"+rej.getCreateName()+"'已驳回,原因："+rej.getContent());
                }
            }
        }

        return LayuiPageFactory.createPageInfo(page);
    }

    private boolean isexist2(List<TaskStatus> taskStatusList, String taskids) {
        if(!CollectionUtil.isNotEmpty(taskStatusList)&& !StringUtils.isEmpty(taskids)){
            return false;
        }

        List<Integer> taskStatusIdList = taskStatusList.stream().map(TaskStatus::getTaskId).collect(Collectors.toList());

        String[] taskidsArr = taskids.split(",");
        int[] array = Arrays.stream(taskidsArr).mapToInt(Integer::parseInt).toArray();
        List<Integer> taskidsList = Arrays.stream(array).boxed().collect(Collectors.toList());
        //取交集-获取taskStatusList中taskids的数据
        taskidsList.retainAll(taskStatusIdList);
        if (taskidsList.size() == taskidsArr.length) {
            return true;
        }else {
            return false;
        }
    }

    private boolean isexist(Integer proId, String taskids) {
        String[] split = taskids.split(",");
        List<TaskStatus> list = taskStatusService.listBytaskids(proId, taskids);
        if (list.size() == split.length) {
            return true;
        } else {
            return false;
        }
    }

    private List<TaskStatus> getTaskStatusListByTaskIds(List<TaskStatus> taskStatusList, String taskids) {
        List<TaskStatus> list = new ArrayList<>();
        String[] split = taskids.split(",");
        for (int i = 0; i < split.length; i++) {
            for (TaskStatus taskStatus : taskStatusList) {
                if (taskStatus.getTaskId() == Integer.parseInt(split[i])) {
                    list.add(taskStatus);
                }
            }
        }
        return list;
    }

    private Serializable getKey(ProjectParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private Project getOldEntity(ProjectParam param) {
        return this.getById(getKey(param));
    }

    private Project getEntity(ProjectParam param) {
        Project entity = new Project();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    @Override
    public void pushMsg2KFZJ(Integer proid, TaskStatus ts) {
        Integer auditResult = ts.getStatus();
        Integer taskid = ts.getTaskId();
        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
        //获取开发总监openid
        List<String> openidlist = userService.listOpenidsByRole(role_kfzj);
        if (ToolUtil.isEmpty(openidlist)) {
            log.error("未找到开发总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//            throw new BusException(BusExceptionEnum.NO_WX_ROLE);
            return;
        }
        String username = null;
        if (ToolUtil.isEmpty(ts.getCreateName())){
            username = LoginContextHolder.getContext().getUser().getName();
        }else {
            username = ts.getCreateName();
        }

        String[] openids = openidlist.toArray(new String[openidlist.size()]);
        Project pro = getById(proid);
        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.AUDIT_TODO == auditResult.intValue()) {
            //判断店名和商务条件是否完成
            String kf_taskids2 = "1,3";
            boolean kf_ts = isexist(proid, kf_taskids2);
            String kfzj_taskids = "6";//开发总监是否确认
            boolean kfzj_ts = isexist(proid, kfzj_taskids);
            //查询工程总监和开发总监审核通过的工程数，，不管营运总监审核结果
            List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_5.getCode() + "," + ProjectTaskEnum.TASK_6.getCode());
            if (kf_ts && !kfzj_ts) {//店名和商务条件完成&zj未确认
                tip = "待审核";
                work = "开发总监确认";
                String[] strs = {work, work, DateUtil.getNow(), "提交人-" + username};
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请尽快审核！已通过" + finishs.size() + "家", strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'开发总监确认'消息已推送给开发总监{}", openids.length);
            }
        } else if (BusConst.PASS == auditResult.intValue()) {
            //营运总监通过
            if (7 == taskid.intValue()){
                tip = "营运总监-" + username + "已通过";
//                String[] strs = {tip, tip, DateUtil.getNow(), tip};
//                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
//                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
//                log.info("'营运总监已通过'消息已推送给开发总监{}", openids.length);

                //工程总监通过
            }else if (5 == taskid.intValue()){

                tip = "工程总监-" + username + "已通过";
//                String[] strs = {tip, tip, DateUtil.getNow(), tip};
//                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
//                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
//                log.info("'工程总监已通过'消息已推送给开发总监{}", openids.length);
            }
            //开发区域经理通过
            else if (62 == taskid.intValue()){
                tip = "开发区域经理-" + username + "已通过";
            }

            String[] strs = {tip, tip, DateUtil.getNow(), tip};
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            log.info(username + "'已通过'消息已推送给开发总监{}", openids.length);

        } else if (BusConst.NOPASS == auditResult.intValue()) {
            //营运总监没通过
            if (7 == taskid.intValue()){
                tip = "营运总监-" + username + "驳回,项目已中止。";
//                String cause = "原因：" + ts.getContent();
//                String[] strs = {tip, tip, DateUtil.getNow(), tip};
//                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), cause, strs);
//                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
//                log.info("'{}'消息已推送给开发总监{}", tip, openids.length);

                //工程总监没通过
            }else if (5 == taskid.intValue()){

                tip = "工程总监-" + username + "驳回。";
//                String cause = "原因：" + ts.getContent();
//                String[] strs = {tip, tip, DateUtil.getNow(), tip};
//                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), cause, strs);
//                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
//                log.info("'{}'消息已推送给开发总监{}", tip, openids.length);
            }
            //开发区域经理没通过
            else if (62 == taskid.intValue()){

                tip = "开发区域经理-" + username + "驳回。";
//                String cause = "原因：" + ts.getContent();
//                String[] strs = {tip, tip, DateUtil.getNow(), tip};
//                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), cause, strs);
//                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
//                log.info("'{}'消息已推送给开发总监{}", tip, openids.length);
            }

            String cause = "原因：" + ts.getContent();
            String[] strs = {tip, tip, DateUtil.getNow(), tip};
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), cause, strs);
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            log.info(username + "'{}'消息已推送给开发总监{}", tip, openids.length);
        }
    }

    @Override
    public void pushMsg2KFQYJL(Integer proid, TaskStatus ts,String qyjlPhone) {
        Integer auditResult = ts.getStatus();
        Integer taskid = ts.getTaskId();
        Long role_kfzj = RoleIdEnum.ROLE_KFQYJL.getCode();//开发区域经理
        //获取开发区域经理openid
        List<String> openidlist = userService.listOpenidsByPhone(role_kfzj,qyjlPhone);
        if (ToolUtil.isEmpty(openidlist)) {
            log.error("未找到开发区域经理微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//            throw new BusException(BusExceptionEnum.NO_WX_ROLE);
            return;
        }
        String username = null;
        if (ToolUtil.isEmpty(ts.getCreateName())){
            username = LoginContextHolder.getContext().getUser().getName();
        }else {
            username = ts.getCreateName();
        }

        String[] openids = openidlist.toArray(new String[openidlist.size()]);
        Project pro = getById(proid);
        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.AUDIT_TODO == auditResult.intValue()) {
            //判断店名和商务条件是否完成
            String kf_taskids2 = "1,3";
            boolean kf_ts = isexist(proid, kf_taskids2);
            String kfzj_taskids = "62";//开发区域经理是否确认
            boolean kfzj_ts = isexist(proid, kfzj_taskids);
            //查询工程总监和开发总监审核通过的工程数，，不管营运总监审核结果
            List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_5.getCode() + "," + ProjectTaskEnum.TASK_6.getCode());
            if (kf_ts && !kfzj_ts) {//店名和商务条件完成&zj未确认
                tip = "待审核";
                work = "开发区域经理确认";
                String[] strs = {work, work, DateUtil.getNow(), "提交人-" + username};
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请尽快审核！已通过" + finishs.size() + "家", strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'开发区域经理确认'消息已推送给开发区域经理确认{}", openids.length);
            }
        }
    }

    @Override
    public void pushMsg2KFZJH5(Integer proid, TaskStatus ts,Long userId) {
        Integer auditResult = ts.getStatus();
        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
        //获取开发总监openid
        List<String> openidlist = userService.listOpenidsByRole(role_kfzj);
        if (ToolUtil.isEmpty(openidlist)) {
            log.error("未找到开发总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//            throw new BusException(BusExceptionEnum.NO_WX_ROLE);
            return;
        }
        String username = null;
        if (ToolUtil.isEmpty(ts.getCreateName())){
            User user=userService.getById(userId);
            if(ToolUtil.isNotEmpty(user)){
                username=user.getName();
            }
        }else {
            username = ts.getCreateName();
        }

        String[] openids = openidlist.toArray(new String[openidlist.size()]);
        Project pro = getById(proid);
        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.AUDIT_TODO == auditResult.intValue()) {
            //判断店名和商务条件是否完成
            String kf_taskids2 = "1,3";
            boolean kf_ts = isexist(proid, kf_taskids2);
            String kfzj_taskids = "6";//开发总监是否确认
            boolean kfzj_ts = isexist(proid, kfzj_taskids);
            //查询工程总监和开发总监审核通过的工程数，，不管营运总监审核结果
            List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_5.getCode() + "," + ProjectTaskEnum.TASK_6.getCode());
            if (kf_ts && !kfzj_ts) {//店名和商务条件完成&zj未确认
                tip = "待审核";
                work = "开发总监确认";
                String[] strs = {work, work, DateUtil.getNow(), "提交人-" + username};
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请尽快审核！已通过" + finishs.size() + "家", strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'开发总监确认'消息已推送给开发总监{}", openids.length);
            }
        } else if (BusConst.PASS == auditResult.intValue()) {//营运总监通过
            tip = "营运总监-" + username + "已通过";
            String[] strs = {tip, tip, DateUtil.getNow(), tip};
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            log.info("'营运总监已通过'消息已推送给开发总监{}", openids.length);
        } else if (BusConst.NOPASS == auditResult.intValue()) {//营运总监没通过
            tip = "营运总监-" + username + "驳回,项目已中止。";
            String cause = "原因：" + ts.getContent();
            String[] strs = {tip, tip, DateUtil.getNow(), tip};
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), cause, strs);
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            log.info("'{}'消息已推送给开发总监{}", tip, openids.length);
        }
    }

    @Override
    public void pushMsg2GCZJ(Integer proid, TaskStatus ts) {
        Integer auditResult = ts.getStatus();
        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
        List<String> openidlist = userService.listOpenidsByRole(role_gczj);
        if (ToolUtil.isEmpty(openidlist)) {
            log.error("未找到工程总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//            throw new BusException(BusExceptionEnum.NO_WX_ROLE);
            return;
        }

        Long userId;
        if (ToolUtil.isEmpty(ts.getCreateId())){
            userId = LoginContextHolder.getContext().getUserId();
        }else {
            userId = ts.getCreateId();
        }
//        Map<String, Object> wx = userService.getWxByUserid(LoginContextHolder.getContext().getUserId());
        Map<String, Object> wx = userService.getWxByUserid(userId);
        String username = null;
        if (ToolUtil.isEmpty(ts.getCreateName())){
            username = LoginContextHolder.getContext().getUser().getName();
        }else {
            username = ts.getCreateName();
        }
//        String username = LoginContextHolder.getContext().getUser().getName();
        if (ToolUtil.isEmpty(wx)) {
            log.error("未获取到当前用户-{} 微信的openid,userid={}", username, userId);
        } else {
            String openid = (String) wx.get("openid");
            if (openidlist.contains(openid)) {
                openidlist.remove(openid);
            }
        }
        String[] openids = openidlist.toArray(new String[openidlist.size()]);
        Project pro = getById(proid);
        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.AUDIT_TODO == auditResult.intValue()) {
            // 判断店名、商务条件、工程条件是否完成
            String kf_taskids3 = "1,2,3";
            boolean kf_ts3 = isexist(proid, kf_taskids3);
            //判断商务总监通过后，再向工程总监推送
            boolean kfzj_ok = isexist(proid, ProjectTaskEnum.TASK_6.getCode().toString());
            if (kf_ts3 && kfzj_ok) {//3个条件完成&开发总监通过了商务条件
                //查询工程总监和开发总监审核通过的工程数，，不管营运总监审核结果
                List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_5.getCode() + "," + ProjectTaskEnum.TASK_6.getCode());

                openids = openidlist.toArray(new String[openidlist.size()]);
                tip = "待审核";
                work = "工程总监确认";
                String[] strs = {work, work, DateUtil.getNow(), "提交人-" + username};
                String remark = "";
                if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                    remark = "工程备注：" + ts.getContent();
                }
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请尽快审核！已通过" + finishs.size() + "家。" + remark, strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'工程总监待确认'消息已推送给工程总监{}", openids.length);
            }
        } else if (BusConst.PASS == auditResult.intValue()) {//gczj||营运总监通过
            if (ProjectTaskEnum.TASK_5.getCode().equals(ts.getTaskId())) {
                tip = "工程总监-" + username + "已通过。";
                if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                    tip = "工程总监-" + username + "已通过。工程备注：" + ts.getContent();
                }
                String[] strs = {tip, tip, DateUtil.getNow(), tip};
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'{}'消息已推送给工程总监{}", tip, openids.length);
            } else if (ProjectTaskEnum.TASK_6.getCode().equals(ts.getTaskId())) {//开发总监确认通过后+ 判断工程条件提交-->向工程总监推送消息。
                String task_gctj = "2";
                boolean gctj_ok = isexist(proid, task_gctj);
                if (gctj_ok) {
                    //查询工程总监和开发总监审核通过的工程数，，不管营运总监审核结果
                    List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_5.getCode() + "," + ProjectTaskEnum.TASK_6.getCode());
//                    tip = "待审核";
                    work = "工程总监确认";
                    Long proCreateUser = pro.getCreateUser();//当前用户为开发总监审核通过
                    User u = userService.getById(proCreateUser);
                    String[] strs = {work, work, DateUtil.getNow(), "提交人-" + u.getName()};
                    String remark = "";
                    if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                        remark = "工程备注：" + ts.getContent();
                    }
                    JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请尽快审核！已通过" + finishs.size() + "家。" + remark, strs);
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                    log.info("'工程总监待确认'消息已推送给工程总监{}", openids.length);
                }
            } else {
                tip = "营运总监-" + username + "已通过";
                String[] strs = {tip, tip, DateUtil.getNow(), tip};
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'{}'消息已推送给工程总监{}", tip, openids.length);
            }

        } else if (BusConst.NOPASS == auditResult.intValue()) {//gczj||营运总监没通过
            if (ProjectTaskEnum.TASK_5.getCode().equals(ts.getTaskId())) {
                tip = "工程总监-" + username + "已驳回";
            } else {
                tip = "营运总监-" + username + "驳回,项目已中止。";
            }
            String[] strs = {tip, tip, DateUtil.getNow(), tip};
            String cause = "原因：" + ts.getContent();
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), cause, strs);
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            log.info("'{}'消息已推送给工程总监{}", tip, openids.length);
        }
    }

    @Override
    public void pushMsg2GCZJH5(Integer proid, TaskStatus ts,Long userId) {
        Integer auditResult = ts.getStatus();
        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
        List<String> openidlist = userService.listOpenidsByRole(role_gczj);
        if (ToolUtil.isEmpty(openidlist)) {
            log.error("未找到工程总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
            return;
        }
        Map<String, Object> wx = userService.getWxByUserid(userId);
        String username = null;
        if (ToolUtil.isEmpty(ts.getCreateName())){
            User user=userService.getById(userId);
            if(ToolUtil.isNotEmpty(user)){
                username=user.getName();
            }
        }else {
            username = ts.getCreateName();
        }
//        String username = LoginContextHolder.getContext().getUser().getName();
        if (ToolUtil.isEmpty(wx)) {
            log.error("未获取到当前用户-{} 微信的openid,userid={}", username, userId);
        } else {
            String openid = (String) wx.get("openid");
            if (openidlist.contains(openid)) {
                openidlist.remove(openid);
            }
        }
        String[] openids = openidlist.toArray(new String[openidlist.size()]);
        Project pro = getById(proid);
        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.AUDIT_TODO == auditResult.intValue()) {
            // 判断店名、商务条件、工程条件是否完成
            String kf_taskids3 = "1,2,3";
            boolean kf_ts3 = isexist(proid, kf_taskids3);
            //判断商务总监通过后，再向工程总监推送
            boolean kfzj_ok = isexist(proid, ProjectTaskEnum.TASK_6.getCode().toString());
            if (kf_ts3 && kfzj_ok) {//3个条件完成&开发总监通过了商务条件
                //查询工程总监和开发总监审核通过的工程数，，不管营运总监审核结果
                List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_5.getCode() + "," + ProjectTaskEnum.TASK_6.getCode());

                openids = openidlist.toArray(new String[openidlist.size()]);
                tip = "待审核";
                work = "工程总监确认";
                String[] strs = {work, work, DateUtil.getNow(), "提交人-" + username};
                String remark = "";
                if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                    remark = "工程备注：" + ts.getContent();
                }
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请尽快审核！已通过" + finishs.size() + "家。" + remark, strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'工程总监待确认'消息已推送给工程总监{}", openids.length);
            }
        } else if (BusConst.PASS == auditResult.intValue()) {//gczj||营运总监通过
            if (ProjectTaskEnum.TASK_5.getCode().equals(ts.getTaskId())) {
                tip = "工程总监-" + username + "已通过。";
                if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                    tip = "工程总监-" + username + "已通过。工程备注：" + ts.getContent();
                }
                String[] strs = {tip, tip, DateUtil.getNow(), tip};
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'{}'消息已推送给工程总监{}", tip, openids.length);
            } else if (ProjectTaskEnum.TASK_6.getCode().equals(ts.getTaskId())) {//开发总监确认通过后+ 判断工程条件提交-->向工程总监推送消息。
                String task_gctj = "2";
                boolean gctj_ok = isexist(proid, task_gctj);
                if (gctj_ok) {
                    //查询工程总监和开发总监审核通过的工程数，，不管营运总监审核结果
                    List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_5.getCode() + "," + ProjectTaskEnum.TASK_6.getCode());
//                    tip = "待审核";
                    work = "工程总监确认";
                    Long proCreateUser = pro.getCreateUser();//当前用户为开发总监审核通过
                    User u = userService.getById(proCreateUser);
                    String[] strs = {work, work, DateUtil.getNow(), "提交人-" + u.getName()};
                    String remark = "";
                    if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                        remark = "工程备注：" + ts.getContent();
                    }
                    JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请尽快审核！已通过" + finishs.size() + "家。" + remark, strs);
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                    log.info("'工程总监待确认'消息已推送给工程总监{}", openids.length);
                }
            } else {
                tip = "营运总监-" + username + "已通过";
                String[] strs = {tip, tip, DateUtil.getNow(), tip};
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'{}'消息已推送给工程总监{}", tip, openids.length);
            }

        } else if (BusConst.NOPASS == auditResult.intValue()) {//gczj||营运总监没通过
            if (ProjectTaskEnum.TASK_5.getCode().equals(ts.getTaskId())) {
                tip = "工程总监-" + username + "已驳回";
            } else {
                tip = "营运总监-" + username + "驳回,项目已中止。";
            }
            String[] strs = {tip, tip, DateUtil.getNow(), tip};
            String cause = "原因：" + ts.getContent();
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), cause, strs);
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            log.info("'{}'消息已推送给工程总监{}", tip, openids.length);
        }
    }

    @Override
    public void pushMsg2YYZJ(Integer proid, TaskStatus taskt) {
        // 判断工程总监,开发总监确认 是否完成
        String taskids = "5,6";
        boolean ts = isexist(proid, taskids);
        if (ts) {//条件完成
            //查询营运总监审核通过的数量
            List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_7.getCode().toString());
            Project pro = getById(proid);
            String tip = "工程条件和商务条件，工程总监和开发总监都审核通过";
            String[] strs = {tip, tip, DateUtil.getNow(), "等待审核"};
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请营运总监审核！已开店" + finishs.size() + "家", strs);
            Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
            List<String> openids = userService.listOpenidsByRole(role_yyzj);
            if (ToolUtil.isEmpty(openids)) {
                log.error("未找到营运总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                return;
            }

            //查询营运总监userID
            List<User> user1 = btyWxMapper.getUser(openids);
            if (ToolUtil.isNotEmpty(user1)) {
                for (User user : user1) {

                    String[] openid = new String[]{user.getOpenid()};

                    //确认开店url
                    String kdUrl = BusConst.KDURL + "&proId=" + proid + "&taskId=7" + "&userId=" + user.getUserId();
                    String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(kdUrl) + type + scope + state;

                    //推送营运总监消息
                    weChatSendTempMsgService.sendmsg(openid, url, param);
                    log.info("=======营运总监确认,推送营运总监消息==========");

                    //消息表中新增推送确认开店消息
                    GcgMsg gcgMsg = new GcgMsg();
                    gcgMsg.setBusinessId(proid);//业务id
                    gcgMsg.setBusinessType("工程");//业务类型
                    gcgMsg.setBusinessName(pro.getName());//业务名称
                    gcgMsg.setTaskId(7);//任务id
                    gcgMsg.setMsgType("确认开店提醒");//消息类型
                    gcgMsg.setMessage(Arrays.toString(strs));//消息内容
                    gcgMsg.setPath(url);//跳转路径
                    gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                    gcgMsg.setSendUser(LoginContextHolder.getContext().getUserId());//发送人id
                    gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                    gcgMsg.setCreateTime(new Date());//创建时间

                    //消息表新增推送确认开店消息
                    msgMapper.insert(gcgMsg);
                }
            }


        }
    }

    @Override
    public void pushMsg2YYZJH5(Integer proid, TaskStatus taskt,Long userId) {
        // 判断工程总监,开发总监确认 是否完成
        String taskids = "5,6";
        boolean ts = isexist(proid, taskids);
        if (ts) {//条件完成
            //查询营运总监审核通过的数量
            List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_7.getCode().toString());
            Project pro = getById(proid);
            String tip = "工程条件和商务条件，工程总监和开发总监都审核通过";
            String[] strs = {tip, tip, DateUtil.getNow(), "等待审核"};
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请营运总监审核！已开店" + finishs.size() + "家", strs);
            Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
            List<String> openids = userService.listOpenidsByRole(role_yyzj);
            if (ToolUtil.isEmpty(openids)) {
                log.error("未找到营运总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                return;
            }

            //查询营运总监userID
            List<User> user1 = btyWxMapper.getUser(openids);
            if (ToolUtil.isNotEmpty(user1)) {
                for (User user : user1) {

                    String[] openid = new String[]{user.getOpenid()};

                    //确认开店url
                    String kdUrl = BusConst.KDURL + "&proId=" + proid + "&taskId=7" + "&userId=" + user.getUserId();
                    String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(kdUrl) + type + scope + state;

                    //推送营运总监消息
                    weChatSendTempMsgService.sendmsg(openid, url, param);
                    log.info("=======营运总监确认,推送营运总监消息==========");

                    //消息表中新增推送确认开店消息
                    GcgMsg gcgMsg = new GcgMsg();
                    gcgMsg.setBusinessId(proid);//业务id
                    gcgMsg.setBusinessType("工程");//业务类型
                    gcgMsg.setBusinessName(pro.getName());//业务名称
                    gcgMsg.setTaskId(7);//任务id
                    gcgMsg.setMsgType("确认开店提醒");//消息类型
                    gcgMsg.setMessage(Arrays.toString(strs));//消息内容
                    gcgMsg.setPath(url);//跳转路径
                    gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                    gcgMsg.setSendUser(userId);//发送人id
                    gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                    gcgMsg.setCreateTime(new Date());//创建时间

                    //消息表新增推送确认开店消息
                    msgMapper.insert(gcgMsg);
                }
            }


        }
    }

    @Override
    public void pushMsg2KFRY(Integer proid, Integer taskid, TaskStatus ts) {
        Integer auditResult = ts.getStatus();
        Project pro = getById(proid);
        Map<String, Object> wx = userService.getWxByUserid(pro.getCreateUser());
        if (ToolUtil.isEmpty(wx)) {
            log.error("未获取到开发人员微信的openid,userid={}", pro.getCreateUser());
            return;
        }
        String username = null;
        if (ToolUtil.isEmpty(ts.getCreateName())){
            username = LoginContextHolder.getContext().getUser().getName();
        }else{
            username = ts.getCreateName();
        }
//        String username = LoginContextHolder.getContext().getUser().getName();
        String openid = (String) wx.get("openid");


        List<String> list = new ArrayList<>();
        list.remove(BusConst.ITZJ);
        list.add(BusConst.ITZJ);
        list.remove(BusConst.GZWX);
        list.add(BusConst.GZWX);
        list.remove(BusConst.CSH);
        list.add(BusConst.CSH);//陈书惠
        list.remove(openid);
        list.add(openid);
        String[] os = list.toArray(new String[list.size()]);


//        String csh = BusConst.CSH;//陈书惠
//        String[] os = {BusConst.ITZJ, BusConst.GZWX, csh, openid};
        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.PASS == auditResult.intValue()) {
            tip = "审核通过";
            if (5 == taskid.intValue()) {
                if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                    tip = "审核通过。工程备注：" + ts.getContent();
                }
                mark = "工程总监-" + username + "已" + tip;
            } else if (6 == taskid.intValue()) {
                mark = "开发总监-" + username + "已" + tip;
            }
            else if (62 == taskid.intValue()) {
                mark = "开发区域经理-" + username + "已" + tip;
            }
            else {
                mark = "营运总监-" + username + "已" + tip;
            }
            work = tip;
        } else {
            if (7 == taskid.intValue()) {
                //营运总监驳回
                tip = "营运总监-" + username + "已驳回,项目已中止。";
//                    work="请重新提交商务条件";
                work = tip;
            }
            else if (62 == taskid.intValue()) {
                //开发区域经理驳回
                tip = "开发区域经理-" + username + "已驳回,";
//                    work="请重新提交商务条件";
                work = tip;
            } else {
                tip = "商务总监-" + username + "审核未通过";
                work = "请重新提交商务条件";
                if (5 == taskid.intValue()) {
                    tip = "工程总监-" + username + "审核未通过";
                    work = work + "和工程条件";
                }
//                    mark=tip+"，"+work;
            }
            mark = "原因：" + ts.getContent();
            pro.setReason(ts.getContent());
        }
        String[] strs = {tip, work, DateUtil.getNow(), tip};
        JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), mark, strs);
        weChatSendTempMsgService.sendmsg(os, BusConst.MSURL, param);
        log.info("'{}'消息已推送给开发人员openid={}", tip, openid);

        //推送小妖app信息
//        pushMsgService.pushToApp(pro, phone, auditResult.intValue());
    }

    @Override
    public void pushMsg2KFRYH5(Integer proid, Integer taskid, TaskStatus ts,Long userId) {
        Integer auditResult = ts.getStatus();
        Project pro = getById(proid);
        Map<String, Object> wx = userService.getWxByUserid(pro.getCreateUser());
        if (ToolUtil.isEmpty(wx)) {
            log.error("未获取到开发人员微信的openid,userid={}", pro.getCreateUser());
            return;
        }
        String username = null;
        if (ToolUtil.isEmpty(ts.getCreateName())){
            User user=userService.getById(userId);
            if(ToolUtil.isNotEmpty(user)){
               username=user.getName();
            }
        }else{
            username = ts.getCreateName();
        }
        String openid = (String) wx.get("openid");


        List<String> list = new ArrayList<>();
        list.remove(BusConst.ITZJ);
        list.add(BusConst.ITZJ);
        list.remove(BusConst.GZWX);
        list.add(BusConst.GZWX);
        list.remove(BusConst.CSH);
        list.add(BusConst.CSH);//陈书惠
        list.remove(openid);
        list.add(openid);
        String[] os = list.toArray(new String[list.size()]);


        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.PASS == auditResult.intValue()) {
            tip = "审核通过";
            if (5 == taskid.intValue()) {
                if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                    tip = "审核通过。工程备注：" + ts.getContent();
                }
                mark = "工程总监-" + username + "已" + tip;
            } else if (6 == taskid.intValue()) {
                mark = "开发总监-" + username + "已" + tip;
            } else {
                mark = "营运总监-" + username + "已" + tip;
            }
            work = tip;
        } else {
            if (7 == taskid.intValue()) {
                //营运总监驳回
                tip = "营运总监-" + username + "已驳回,项目已中止。";
//                    work="请重新提交商务条件";
                work = tip;
            } else {
                tip = "商务总监-" + username + "审核未通过";
                work = "请重新提交商务条件";
                if (5 == taskid.intValue()) {
                    tip = "工程总监-" + username + "审核未通过";
                    work = work + "和工程条件";
                }
            }
            mark = "原因：" + ts.getContent();
        }
        String[] strs = {tip, work, DateUtil.getNow(), tip};
        JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), mark, strs);
        weChatSendTempMsgService.sendmsg(os, BusConst.MSURL, param);
        log.info("'{}'消息已推送给开发人员openid={}", tip, openid);
    }


    /**
     * 通知开发人员审核通过
     * @param proid
     * @param taskid
     * @param ts
     */
    @Override
    public void pushKFRY(Integer proid, Integer taskid, TaskStatus ts) {
        Integer auditResult = ts.getStatus();
        Project pro = getById(proid);
        Map<String, Object> wx = userService.getWxByUserid(pro.getCreateUser());
        if (ToolUtil.isEmpty(wx)) {
            log.error("未获取到开发人员微信的openid,userid={}", pro.getCreateUser());
            return;
        }
        String username = null;
        if (ToolUtil.isEmpty(ts.getCreateName())){
            username = LoginContextHolder.getContext().getUser().getName();
        }else {
            username = ts.getCreateName();
        }
//        String username = LoginContextHolder.getContext().getUser().getName();
        //开发人员openID
        String openid = (String) wx.get("openid");
        String[] kfOpenid = {openid};

        String csh = BusConst.CSH;//陈书惠
        String[] os = {BusConst.ITZJ, BusConst.GZWX, csh};
        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.PASS == auditResult.intValue()) {
            tip = "审核通过";
            if (5 == taskid.intValue()) {
                if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                    tip = "审核通过。工程备注：" + ts.getContent();
                }
                mark = "工程总监-" + username + "已" + tip;
            } else if (6 == taskid.intValue()) {
                mark = "开发总监-" + username + "已" + tip;
            }else if (62 == taskid.intValue()) {
                mark = "开发区域经理-" + username + "已" + tip;
            } else {
                mark = "营运总监-" + username + "已" + tip;
            }
            work = tip;
        }
        String[] strs = {tip, work, DateUtil.getNow(), tip};
        JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), mark, strs);
        weChatSendTempMsgService.sendmsg(os, BusConst.MSURL, param);
        log.info("'{}'消息已推送给张总openid={}", tip, openid);


        //通知开发人员审核通过url
        String syUrl = BusConst.WGURL + "&proId=" + proid + "&taskId=" + taskid + "&userId=" + pro.getCreateUser();
        String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

        //通知开发人员审核通过
        weChatSendTempMsgService.sendmsg(kfOpenid, url, param);
        log.info("=======通知开发人员审核通过==========");

        //消息表中新增通知开发人员审核通过消息
        GcgMsg gcgMsg = new GcgMsg();
        gcgMsg.setBusinessId(proid);//业务id
        gcgMsg.setBusinessType("工程");//业务类型
        gcgMsg.setBusinessName(pro.getName());//业务名称
        gcgMsg.setTaskId(taskid);//任务id
        gcgMsg.setMsgType("通知开发人员审核通过提醒");//消息类型
        gcgMsg.setMessage(mark);//消息内容
        gcgMsg.setPath(url);//跳转路径
        gcgMsg.setTaskStatus(0);//任务状态;0->已完成，1->未完成
        if (ToolUtil.isEmpty(ts.getCreateName())){
            gcgMsg.setSendUser(LoginContextHolder.getContext().getUserId());//当前登录者id
        }else {
            gcgMsg.setSendUser(ts.getCreateId());//当前登录者id
        }
        gcgMsg.setReceiveUser(pro.getCreateUser());//接收人ID
        gcgMsg.setCreateTime(new Date());//创建时间

        //消息表新增无完工日期提醒数据
        msgMapper.insert(gcgMsg);


    }

    /**
     * 通知开发人员审核通过
     * @param proid
     * @param taskid
     * @param ts
     */
    @Override
    public void pushKFRYH5(Integer proid, Integer taskid, TaskStatus ts,Long userId) {
        Integer auditResult = ts.getStatus();
        Project pro = getById(proid);
        Map<String, Object> wx = userService.getWxByUserid(pro.getCreateUser());
        if (ToolUtil.isEmpty(wx)) {
            log.error("未获取到开发人员微信的openid,userid={}", pro.getCreateUser());
            return;
        }
        String username = null;
        if (ToolUtil.isEmpty(ts.getCreateName())){
            User user=userService.getById(userId);
            if(ToolUtil.isNotEmpty(user)){
                username=user.getName();
            }
        }else {
            username = ts.getCreateName();
        }
        //开发人员openID
        String openid = (String) wx.get("openid");
        String[] kfOpenid = {openid};

        String csh = BusConst.CSH;//陈书惠
        String[] os = {BusConst.ITZJ, BusConst.GZWX, csh};
        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.PASS == auditResult.intValue()) {
            tip = "审核通过";
            if (5 == taskid.intValue()) {
                if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                    tip = "审核通过。工程备注：" + ts.getContent();
                }
                mark = "工程总监-" + username + "已" + tip;
            } else if (6 == taskid.intValue()) {
                mark = "开发总监-" + username + "已" + tip;
            } else {
                mark = "营运总监-" + username + "已" + tip;
            }
            work = tip;
        }
        String[] strs = {tip, work, DateUtil.getNow(), tip};
        JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), mark, strs);
        weChatSendTempMsgService.sendmsg(os, BusConst.MSURL, param);
        log.info("'{}'消息已推送给张总openid={}", tip, openid);


        //通知开发人员审核通过url
        String syUrl = BusConst.WGURL + "&proId=" + proid + "&taskId=" + taskid + "&userId=" + pro.getCreateUser();
        String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

        //通知开发人员审核通过
        weChatSendTempMsgService.sendmsg(kfOpenid, url, param);
        log.info("=======通知开发人员审核通过==========");

        //消息表中新增通知开发人员审核通过消息
        GcgMsg gcgMsg = new GcgMsg();
        gcgMsg.setBusinessId(proid);//业务id
        gcgMsg.setBusinessType("工程");//业务类型
        gcgMsg.setBusinessName(pro.getName());//业务名称
        gcgMsg.setTaskId(taskid);//任务id
        gcgMsg.setMsgType("通知开发人员审核通过提醒");//消息类型
        gcgMsg.setMessage(mark);//消息内容
        gcgMsg.setPath(url);//跳转路径
        gcgMsg.setTaskStatus(0);//任务状态;0->已完成，1->未完成
        if (ToolUtil.isEmpty(ts.getCreateName())){
            gcgMsg.setSendUser(userId);//当前登录者id
        }else {
            gcgMsg.setSendUser(ts.getCreateId());//当前登录者id
        }
        gcgMsg.setReceiveUser(pro.getCreateUser());//接收人ID
        gcgMsg.setCreateTime(new Date());//创建时间

        //消息表新增无完工日期提醒数据
        msgMapper.insert(gcgMsg);


    }


    @Override
    public void pushMsg2KFRYadmin(Integer proid, Integer taskid, TaskStatus ts) {
        Project pro = getById(proid);
        Long proCreatUserid = pro.getCreateUser();
        LoginUser crutUser = LoginContextHolder.getContext().getUser();
        String crutUsername =crutUser.getName();

        Integer auditResult = ts.getStatus();
        if(crutUser.getId().longValue()!=proCreatUserid.longValue()){//管理员不是开发人员时，推送开发人员消息
            Map<String, Object> wx = userService.getWxByUserid(proCreatUserid);
            if (ToolUtil.isEmpty(wx)) {
                log.error("未获取到开发人员微信的openid,userid={}", proCreatUserid);
                return;
            }
            String openid = (String) wx.get("openid");
            String[] os = {openid};
            String tip = "提示";
            String work = "";
            String mark = "";
            String[] strs=null;
            if(taskid.intValue()==ProjectTaskEnum.TASK_3.getCode().intValue()){
                work="你创建的工程，'商务条件'已由工程管理员-"+crutUsername+"提交";
                mark =work;
                strs = new String[]{tip, tip, DateUtil.getNow(), work};
            }else if(taskid.intValue()==ProjectTaskEnum.TASK_2.getCode().intValue()){
                work="你创建的工程，'工程条件'已由工程管理员-"+crutUsername+"提交";
                mark =work;
                strs = new String[]{tip, tip, DateUtil.getNow(), work};
            }else if(taskid.intValue()==ProjectTaskEnum.TASK_5.getCode().intValue()){
                work="你创建的工程，'工程总监确认'已由工程管理员-"+crutUsername;
                if (BusConst.PASS == auditResult.intValue()) {
                    work+="审核通过";
                    mark =work;
                    strs = new String[]{tip, tip, DateUtil.getNow(), work};
                }else{
                    work+="驳回,请重新提交商务条件和工程条件";
                    mark = "原因：" + ts.getContent();
                    strs = new String[]{tip, tip, DateUtil.getNow(), work};
                }
            }else if(taskid.intValue()==ProjectTaskEnum.TASK_6.getCode().intValue()){
                work="你创建的工程，'开发总监确认'已由工程管理员-"+crutUsername;
                if (BusConst.PASS == auditResult.intValue()) {
                    work+="审核通过";
                    mark =work;
                    strs = new String[]{tip, tip, DateUtil.getNow(), work};
                }else{
                    work+="驳回,请重新提交商务条件";
                    mark = "原因：" + ts.getContent();
                    strs = new String[]{tip, tip, DateUtil.getNow(), work};
                }
            }else if(taskid.intValue()==ProjectTaskEnum.TASK_7.getCode().intValue()){
                work="你创建的工程，'营运总监确认'已由工程管理员-"+crutUsername;
                if (BusConst.PASS == auditResult.intValue()) {
                    work+="审核通过";
                    mark =work;
                    strs = new String[]{tip, tip, DateUtil.getNow(), work};
                }else{
                    work+="驳回,项目已中止。";
                    mark = "原因：" + ts.getContent();
                    strs = new String[]{tip, tip, DateUtil.getNow(), work};
                }
            }
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), mark, strs);
            weChatSendTempMsgService.sendmsg(os, BusConst.MSURL, param);
            log.info("消息已推送给开发人员{}",proid);
        }

    }

//    @Override
    public void pushMsg2GCZJadmin2(Integer proid, TaskStatus ts) {
        Project pro = getById(proid);
        Integer auditResult = ts.getStatus();
        LoginUser crutUser = LoginContextHolder.getContext().getUser();
        String crutUsername =crutUser.getName();

        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监

        String tip="提示";
        String work = "";
        String mark = "";
        String[] strs=null;
        JSONObject param=new JSONObject();
        if(ts.getTaskId().intValue()==ProjectTaskEnum.TASK_5.getCode().intValue()){//工程总监确认后通知其他工程总监
            mark="'工程总监确认'已由工程管理员-"+crutUsername;
            if (BusConst.PASS == auditResult.intValue()) {
                mark+="审核通过";
                strs = new String[]{tip, tip, DateUtil.getNow(), mark};
                param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), mark, strs);
            }else{
                List<String> openidlist = userService.listOpenidsByRole(role_gczj);
                String[] openids = openidlist.toArray(new String[openidlist.size()]);
                if (ToolUtil.isEmpty(openidlist)) {
                    log.error("未找到工程总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                    throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                    return;
                }
                mark+="驳回";
                String cause = "原因：" + ts.getContent();
                strs = new String[]{tip, tip, DateUtil.getNow(), mark};
//                param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), cause, strs);
//                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            }

        }else if(ts.getTaskId().intValue()==ProjectTaskEnum.TASK_7.getCode().intValue()){//营运总监确认
            mark="'营运总监确认'已由工程管理员-"+crutUsername;
            if (BusConst.PASS == auditResult.intValue()) {

            }else{

                String cause = "原因：" + ts.getContent();
                strs = new String[]{tip, tip, DateUtil.getNow(), tip};

            }
        }
//        JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), mark, strs);
//        weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);

    }

    @Override
    public void pushMsg2KFZJadmin(Integer proid, TaskStatus ts) {
        Integer auditResult = ts.getStatus();
        Integer taskid = ts.getTaskId();
        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
        //获取开发总监openid
        List<String> openidlist = userService.listOpenidsByRole(role_kfzj);
        if (ToolUtil.isEmpty(openidlist)) {
            log.error("未找到开发总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//            throw new BusException(BusExceptionEnum.NO_WX_ROLE);
            return;
        }
        String username = LoginContextHolder.getContext().getUser().getName();

        openidlist.remove(BusConst.ITZJ);
        openidlist.add(BusConst.ITZJ);
        openidlist.remove(BusConst.GZWX);
        openidlist.add(BusConst.GZWX);
        openidlist.remove(BusConst.CSH);
        openidlist.add(BusConst.CSH);//陈书惠
        String[] openids = openidlist.toArray(new String[openidlist.size()]);
        Project pro = getById(proid);
        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.AUDIT_TODO == auditResult.intValue()) {
            //判断店名和商务条件是否完成
            String kf_taskids2 = "1,3";
            boolean kf_ts = isexist(proid, kf_taskids2);
            String kfzj_taskids = "6";//开发总监是否确认
            boolean kfzj_ts = isexist(proid, kfzj_taskids);
            //查询工程总监和开发总监审核通过的工程数，，不管营运总监审核结果
            List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_5.getCode() + "," + ProjectTaskEnum.TASK_6.getCode());
            if (kf_ts && !kfzj_ts) {//店名和商务条件完成&zj未确认
                tip = "待审核";
                work = "开发总监确认";
                String[] strs = {work, work, DateUtil.getNow(), "提交人-" + username};
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请尽快审核！已通过" + finishs.size() + "家", strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'开发总监确认'消息已推送给开发总监{}", openids.length);
            }
        } else if (BusConst.PASS == auditResult.intValue()) {
            //营运总监通过
            if (7 == taskid.intValue()){
                tip = "营运总监-" + username + "已通过";

                //工程总监通过
            }else if (5 == taskid.intValue()){
                tip = "工程总监-" + username + "已通过";
            }

            String[] strs = {tip, tip, DateUtil.getNow(), tip};
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            log.info(username + "'已通过'消息已推送给开发总监{}", openids.length);

        } else if (BusConst.NOPASS == auditResult.intValue()) {
            //营运总监没通过
            if (7 == taskid.intValue()){
                tip = "营运总监-" + username + "驳回,项目已中止。";
                //工程总监通过
            }else if (5 == taskid.intValue()){
                tip = "营运总监-" + username + "驳回。";
            }

            String cause = "原因：" + ts.getContent();
            String[] strs = {tip, tip, DateUtil.getNow(), tip};
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), cause, strs);
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            log.info(username + "'{}'消息已推送给开发总监{}", tip, openids.length);
        }
    }

    @Override
    public void pushMsg2GCZJadmin(Integer proid, TaskStatus ts) {
        Integer auditResult = ts.getStatus();
        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
        List<String> openidlist = userService.listOpenidsByRole(role_gczj);
        if (ToolUtil.isEmpty(openidlist)) {
            log.error("未找到工程总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//            throw new BusException(BusExceptionEnum.NO_WX_ROLE);
            return;
        }
        Map<String, Object> wx = userService.getWxByUserid(LoginContextHolder.getContext().getUserId());
        String username = LoginContextHolder.getContext().getUser().getName();
        if (ToolUtil.isNotEmpty(wx)) {
            String openid = (String) wx.get("openid");
            if (openidlist.contains(openid)) {
                openidlist.remove(openid);
            }
        }
        String[] openids = openidlist.toArray(new String[openidlist.size()]);
        Project pro = getById(proid);
        String tip = "";
        String work = "";
        String mark = "";
        if (BusConst.AUDIT_TODO == auditResult.intValue()) {
            // 判断店名、商务条件、工程条件是否完成
            String kf_taskids3 = "1,2,3";
            boolean kf_ts3 = isexist(proid, kf_taskids3);
            //判断商务总监通过后，再向工程总监推送
            boolean kfzj_ok = isexist(proid, ProjectTaskEnum.TASK_6.getCode().toString());
            if (kf_ts3 && kfzj_ok) {//3个条件完成&开发总监通过了商务条件
                //查询工程总监和开发总监审核通过的工程数，，不管营运总监审核结果
                List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_5.getCode() + "," + ProjectTaskEnum.TASK_6.getCode());
                openidlist.remove(BusConst.ITZJ);
                openidlist.add(BusConst.ITZJ);
                openidlist.remove(BusConst.GZWX);
                openidlist.add(BusConst.GZWX);
                openidlist.remove(BusConst.CSH);
                openidlist.add(BusConst.CSH);//陈书惠
                openids = openidlist.toArray(new String[openidlist.size()]);
                tip = "待审核";
                work = "工程总监确认";
                String[] strs = {work, work, DateUtil.getNow(), "提交人-" + username};
                String remark = "";
                if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                    remark = "工程备注：" + ts.getContent();
                }
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请尽快审核！已通过" + finishs.size() + "家。" + remark, strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'工程总监待确认'消息已推送给工程总监{}", openids.length);
            }
        } else if (BusConst.PASS == auditResult.intValue()) {//gczj||营运总监通过
            if (ProjectTaskEnum.TASK_5.getCode().equals(ts.getTaskId())) {
                tip = "工程总监-" + username + "已通过。";
                if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                    tip = "工程总监-" + username + "已通过。工程备注：" + ts.getContent();
                }
                String[] strs = {tip, tip, DateUtil.getNow(), tip};
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'{}'消息已推送给工程总监{}", tip, openids.length);
            } else if (ProjectTaskEnum.TASK_6.getCode().equals(ts.getTaskId())) {//开发总监确认通过后+ 判断工程条件提交-->向工程总监推送消息。
                String task_gctj = "2";
                boolean gctj_ok = isexist(proid, task_gctj);
                if (gctj_ok) {
                    //查询工程总监和开发总监审核通过的工程数，，不管营运总监审核结果
                    List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_5.getCode() + "," + ProjectTaskEnum.TASK_6.getCode());
//                    tip = "待审核";
                    work = "工程总监确认";
                    Long proCreateUser = pro.getCreateUser();//当前用户为开发总监审核通过
                    User u = userService.getById(proCreateUser);
                    String[] strs = {work, work, DateUtil.getNow(), "提交人-" + u.getName()};
                    String remark = "";
                    if (ts.getContent() != null && ts.getContent() != "" && ts.getContent() != "无") {
                        remark = "工程备注：" + ts.getContent();
                    }
                    JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请尽快审核！已通过" + finishs.size() + "家。" + remark, strs);
                    weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                    log.info("'工程总监待确认'消息已推送给工程总监{}", openids.length);
                }
            } else {
                tip = "营运总监-" + username + "已通过";
                String[] strs = {tip, tip, DateUtil.getNow(), tip};
                JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), tip, strs);
                weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
                log.info("'{}'消息已推送给工程总监{}", tip, openids.length);
            }

        } else if (BusConst.NOPASS == auditResult.intValue()) {//gczj||营运总监没通过
            if (ProjectTaskEnum.TASK_5.getCode().equals(ts.getTaskId())) {
                tip = "工程总监-" + username + "已驳回";
            } else {
                tip = "营运总监-" + username + "驳回,项目已中止。";
            }
            String[] strs = {tip, tip, DateUtil.getNow(), tip};
            String cause = "原因：" + ts.getContent();
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), cause, strs);
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            log.info("'{}'消息已推送给工程总监{}", tip, openids.length);
        }
    }

    @Override
    public void pushMsg2YYZJadmin(Integer proid, TaskStatus taskt) {
        // 判断工程总监,开发总监确认 是否完成
        String taskids = "5,6";
        boolean ts = isexist(proid, taskids);
        if (ts) {//条件完成
            //查询营运总监审核通过的数量
            List<Integer> finishs = taskStatusService.listAuditFinish(ProjectTaskEnum.TASK_7.getCode().toString());
            Project pro = getById(proid);
            String tip = "工程条件和商务条件，工程总监和开发总监都审核通过";
            String[] strs = {tip, tip, DateUtil.getNow(), "等待审核"};
            JSONObject param = weChatSendTempMsgService.setTempParam(proid + "." + pro.getName(), "请营运总监审核！已开店" + finishs.size() + "家", strs);
            Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
            List<String> openids = userService.listOpenidsByRole(role_yyzj);
            if (ToolUtil.isEmpty(openids)) {
                log.error("未找到营运总监微信openid,{}", BusExceptionEnum.NO_WX_ROLE);
//                throw new BusException(BusExceptionEnum.NO_WX_ROLE);
                return;
            }
            openids.remove(BusConst.ITZJ);
            openids.add(BusConst.ITZJ);
            openids.remove(BusConst.GZWX);
            openids.add(BusConst.GZWX);
            openids.remove(BusConst.CSH);
            openids.add(BusConst.CSH);//陈书惠
            weChatSendTempMsgService.sendmsg(openids.toArray(new String[openids.size()]), BusConst.MSURL, param);
            log.info("'营运总监确认'消息已推送给营运总监{}", openids.size());
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGcyyjlAdmin(ProjectParam record) {
        String[] errwords = {"消息通知", "消息通知", DateUtil.getNow(), ""};
        if (ToolUtil.isOneEmpty(record, record.getId(), record.getYyjl())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        boolean isexist = isexist(record.getId(), ProjectTaskEnum.TASK_7.getCode().toString());
        if(!isexist){
            throw new ServiceException(BusExceptionEnum.ERR_NO_YYZJOK);
        }
        /*//根据yyjl查找手机
        String name = record.getYyjl();
//        String tel = btyArchivesMapper.getTelByName(name);
        Map<String, Object> map = new HashMap<>();
        map.put("xm", name);
        BtyArchives arch = btyArchivesMapper.getObjByCon(map);*/
        Project pro = getById(record.getId());
        String oldyyjl = pro.getYyjl();
//        Map<String, Object> wx = userService.getWxByUserid(LoginContextHolder.getContext().getUserId());
        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//开发总监
        //获取营运总监openid
        List<String> yyzjopenidlist = userService.listOpenidsByRole(role_yyzj);
        if (ToolUtil.isEmpty(yyzjopenidlist)) {
            log.error("未获取到营运总监微信");
        }
        String[] yyzjOpenids = yyzjopenidlist.toArray(new String[yyzjopenidlist.size()]);
//        String yyzjopenid = (String) wx.get("openid");
        String name = record.getYyjl();
        String tel = record.getTel().trim();
        if (ToolUtil.isEmpty(tel)) {
            log.error("营运经理-{}未绑定手机!", record.getYyjl());
            errwords[3] = "指定营运经理失败："+name+"-" + BusExceptionEnum.NO_PHONE.getMessage();
            JSONObject errparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), errwords[3], errwords);
            //报错时，推送给营运总监失败
            weChatSendTempMsgService.sendmsg(yyzjOpenids, BusConst.MSURL, errparam);
            throw new BusException(BusExceptionEnum.NO_PHONE);
        }
        record.setYyjl(tel);
        int i = baseMapper.updateProjectByCondition(record);
        if (i > 0) {
            //保存taskstatus
            TaskStatusParam ts = new TaskStatusParam();
            ts.setProId(record.getId());
            ts.setTaskId(40);
            ts.setStatus(1);
            int tsExist = taskStatusService.selectStau(ts);
            if (tsExist == 0){
                taskStatusService.add(ts);
            }else {
                taskStatusService.updateAuditSt(ts);
            }

            //保存flow
            TaskFlowParam flow = new TaskFlowParam();
            flow.setProId(record.getId());
            flow.setTaskId(40);
            flow.setStatus(1);
            flow.setCreateUser(LoginContextHolder.getContext().getUser().getId());
            taskFlowService.add(flow);

            //修改通讯录营运经理
            if (ToolUtil.isNotEmpty(pro.getYaoma())){
                BtyTxl btyTxl = new BtyTxl();
                btyTxl.setYytel(tel);
                btyTxl.setYyjlqy(name);
                btyTxl.setCtbh(pro.getYaoma());
                btyTxlMapper.updateTxlYy(btyTxl);
            }


            //推送营运经理通知
            String[] strs = {"消息通知", "消息通知", DateUtil.getNow(), "已指定您为该店营运经理，请指定督导"};
            JSONObject param = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), name + ",请指定督导！", strs);
            List<BtyWx> wxs = btyWxService.getWx(tel);
            //营运经理
            List<String> openidlist = getOpenids(wxs);
            if (ToolUtil.isEmpty(openidlist)) {
                log.error("{},营运经理-{}", BusExceptionEnum.NO_WX.getMessage(), name);
                errwords[3] = "指定营运经理失败：" + BusExceptionEnum.NO_WX.getMessage();
                JSONObject errparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), errwords[3], errwords);
                //报错时，推送给营运总监失败
                weChatSendTempMsgService.sendmsg(yyzjOpenids, BusConst.MSURL, errparam);
                throw new BusException(BusExceptionEnum.NO_WX);
            }
//            openidlist.remove(BusConst.ITZJ);
//            openidlist.add(BusConst.ITZJ);
//            openidlist.remove(BusConst.GZWX);
//            openidlist.add(BusConst.GZWX);
//            openidlist.remove(BusConst.CSH);
//            openidlist.add(BusConst.CSH);//陈书惠
            String[] openids = openidlist.toArray(new String[openidlist.size()]);
            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, param);
            log.info("'营运经理已保存'通知并推送给营运经理-{}", name);

            if(tsExist>0){
                //推送给旧的营运经理
                List<BtyWx> oldwxs = btyWxService.getWx(oldyyjl);
                List<String> oldopenidList = getOpenids(oldwxs);
                String[] oldOpenids = oldopenidList.toArray(new String[oldopenidList.size()]);
                String[] oldstrs = {"消息通知", "消息通知", DateUtil.getNow(), "由你负责的店,营运经理已变更为"+name};
                JSONObject oldparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(),  "由你负责的店,营运经理已变更为"+name, oldstrs);
                weChatSendTempMsgService.sendmsg(oldOpenids, BusConst.MSURL, oldparam);
            }
            //推送给开发人员 yyjl的信息
            Map<String, Object> kfrywx = userService.getWxByUserid(pro.getCreateUser());
            if (ToolUtil.isEmpty(kfrywx)) {
                log.error("未获取到开发人员微信的openid,userid={}", pro.getCreateUser());
                return;
            }
            String openid = (String) kfrywx.get("openid");
            String[] os = {openid};
            String[] str2 = {"消息通知", "消息通知", DateUtil.getNow(), "该工程已分派营运经理"};
            JSONObject kfryjs = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), "营运经理：" + name + ",电话：" + tel, str2);
            weChatSendTempMsgService.sendmsg(os, BusConst.MSURL, kfryjs);
            log.info("'营运经理已保存'通知并推送给{}", name);


            //刘书伟
            String[] openidsLiu = new String[]{BusConst.LSW};
            String data = pro.getName() + "已确定开店，请确认店名是否合适！";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(pro.getName(), "已确定开店，请确认店名是否合适！", "消息通知", "消息通知", DateUtil.getNow(), data);
            //推送消息
            weChatSendTempMsgService.sendmsg(openidsLiu, BusConst.MSURL, tempObj);
            log.info("=======推送收刘书伟消息==========");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGcyyjl(ProjectParam record) {
        String[] errwords = {"消息通知", "消息通知", DateUtil.getNow(), ""};
        if (ToolUtil.isOneEmpty(record, record.getId(), record.getYyjl())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        /*//根据yyjl查找手机taskId
        String name = record.getYyjl();
//        String tel = btyArchivesMapper.getTelByName(name);
        Map<String, Object> map = new HashMap<>();
        map.put("xm", name);
        BtyArchives arch = btyArchivesMapper.getObjByCon(map);*/
        Project pro = getById(record.getId());
        String oldyyjl = pro.getYyjl();
        String name = record.getYyjl();
        String tel = record.getTel().trim();
        if(ToolUtil.isNotEmpty(oldyyjl) && oldyyjl.equals(tel)){//如果两次人相同，不再处理
            return;
        }

        Long userId;
        String userName;
        if (ToolUtil.isEmpty(record.getCreateUser())){
            userId = LoginContextHolder.getContext().getUserId();
            userName = LoginContextHolder.getContext().getUser().getName();
        }else {
            userId = record.getCreateUser();
            userName = userMapper.getName(record.getCreateUser());
        }

        Map<String, Object> wx = userService.getWxByUserid(userId);
        if (ToolUtil.isEmpty(wx)) {
            log.error("未获取到营运总监-{} 微信的openid,userid={}", userName, userId);
        }
        String yyzjopenid = (String) wx.get("openid");

        if (ToolUtil.isEmpty(record.getTel())) {
            log.error("营运经理-{}未绑定手机!", record.getYyjl());
            errwords[3] = "指定营运经理失败："+name+"-" + BusExceptionEnum.NO_PHONE.getMessage();
            JSONObject errparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), errwords[3], errwords);
            //报错时，推送给营运总监失败
            weChatSendTempMsgService.sendmsg(yyzjopenid.split(","), BusConst.MSURL, errparam);
            throw new BusException(BusExceptionEnum.NO_PHONE);
        }
        record.setYyjl(tel);
        record.setUpdateTime(new Date());
        int i = baseMapper.updateProjectByCondition(record);
        if (i > 0) {
            //保存taskstatus
            TaskStatusParam ts = new TaskStatusParam();
            ts.setProId(record.getId());
            ts.setTaskId(40);
            ts.setStatus(1);
            if (ToolUtil.isNotEmpty(record.getCreateUser())){
                ts.setCreateUser(record.getCreateUser());
            }
            int tsExist = taskStatusService.selectStau(ts);
            if (tsExist == 0){
                taskStatusService.add(ts);
            }else {
                taskStatusService.updateAuditSt(ts);
            }

            //保存flow
            TaskFlowParam flow = new TaskFlowParam();
            flow.setProId(record.getId());
            flow.setTaskId(40);
            flow.setStatus(1);
            if (ToolUtil.isNotEmpty(record.getCreateUser())){
                flow.setCreateUser(record.getCreateUser());
            }else {
                flow.setCreateUser(LoginContextHolder.getContext().getUser().getId());
            }
            taskFlowService.add(flow);
            taskStatusService.insertNextNode(ts);//插入下个节点

            //修改通讯录营运经理
            if (ToolUtil.isNotEmpty(pro.getYaoma())){
                BtyTxl btyTxl = new BtyTxl();
                btyTxl.setYytel(tel);
                btyTxl.setYyjlqy(name);
                btyTxl.setCtbh(pro.getYaoma());
                btyTxlMapper.updateTxlYy(btyTxl);
            }

            //推送营运经理通知
            String[] strs = {"消息通知", "消息通知", DateUtil.getNow(), "已指定您为该店营运经理，请指定督导"};
            JSONObject param = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), name + ",请指定督导！", strs);
            List<BtyWx> wxs = btyWxService.getWx(tel);
            //营运经理
            List<String> openidlist = getOpenids(wxs);
            if (ToolUtil.isEmpty(openidlist)) {
                log.error("{},营运经理-{}", BusExceptionEnum.NO_WX.getMessage(), name);
                errwords[3] = "指定营运经理失败：" + BusExceptionEnum.NO_WX.getMessage();
                JSONObject errparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), errwords[3], errwords);
                //报错时，推送给营运总监失败
                weChatSendTempMsgService.sendmsg(yyzjopenid.split(","), BusConst.MSURL, errparam);
                throw new BusException(BusExceptionEnum.NO_WX);
            }

            String[] openids = openidlist.toArray(new String[openidlist.size()]);

            //营运经理
            List<User> user1 = btyWxMapper.getUser(openidlist);
            if (ToolUtil.isNotEmpty(user1)) {
                for (User user : user1) {
                    //指定督导
                    String syUrl = BusConst.DDURL + "&proId=" + record.getId() + "&taskId=41" + "&userId=" + user.getUserId();
                    String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                    //推送营运经理消息
                    weChatSendTempMsgService.sendmsg(openids, url, param);
                    log.info("=======营运经理已保存'通知并推送给营运经理-{}==========");

                    //消息表中新增推送指定营运经理消息
                    GcgMsg gcgMsg = new GcgMsg();
                    gcgMsg.setBusinessId(record.getId());//业务id
                    gcgMsg.setBusinessType("工程");//业务类型
                    gcgMsg.setBusinessName(pro.getName());//业务名称
                    gcgMsg.setTaskId(40);//任务id
                    gcgMsg.setMsgType("指定营运经理提醒");//消息类型
                    gcgMsg.setMessage(Arrays.toString(strs));//消息内容
                    gcgMsg.setPath(url);//跳转路径
                    gcgMsg.setTaskStatus(0);//任务状态;0->已完成，1->未完成
                    if (ToolUtil.isNotEmpty(record.getCreateUser())){
                        gcgMsg.setSendUser(record.getCreateUser());//发送人id
                    }else {
                        gcgMsg.setSendUser(LoginContextHolder.getContext().getUserId());//发送人id
                    }
                    gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                    gcgMsg.setCreateTime(new Date());//创建时间

                    //消息表新增出图日期消息
                    msgMapper.insert(gcgMsg);
                }
            }

            if(tsExist>0){
                //推送给旧的营运经理
                List<BtyWx> oldwxs = btyWxService.getWx(oldyyjl);
                List<String> oldopenidList = getOpenids(oldwxs);
                String[] oldOpenids = oldopenidList.toArray(new String[oldopenidList.size()]);
                String[] oldstrs = {"消息通知", "消息通知", DateUtil.getNow(), "由你负责的店,营运经理已变更为"+name};
                JSONObject oldparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(),  "由你负责的店,营运经理已变更为"+name, oldstrs);
                weChatSendTempMsgService.sendmsg(oldOpenids, BusConst.MSURL, oldparam);
            }
            //推送给开发人员 yyjl的信息
            Map<String, Object> kfrywx = userService.getWxByUserid(pro.getCreateUser());
            if (ToolUtil.isEmpty(kfrywx)) {
                log.error("未获取到开发人员微信的openid,userid={}", pro.getCreateUser());
                return;
            }
            String openid = (String) kfrywx.get("openid");
            String[] os = {openid};
            String[] str2 = {"消息通知", "消息通知", DateUtil.getNow(), "该工程已分派营运经理"};
            JSONObject kfryjs = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), "营运经理：" + name + ",电话：" + tel, str2);
            weChatSendTempMsgService.sendmsg(os, BusConst.MSURL, kfryjs);
            log.info("'营运经理已保存'通知并推送给{}", name);


            //刘书伟
            String[] openidsLiu = new String[]{BusConst.LSW};
            String data = pro.getName() + "已确定开店，请确认店名是否合适！";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(pro.getName(), null, "消息通知", "消息通知", DateUtil.getNow(), data);
            //推送消息
            weChatSendTempMsgService.sendmsg(openidsLiu, BusConst.MSURL, tempObj);
            log.info("=======推送收刘书伟消息==========");
        }
    }

    /**
     * 手机端
     * @param record
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData saveGcWxyyjl(ProjectParam record) {
        String[] errwords = {"消息通知", "消息通知", DateUtil.getNow(), ""};
        if (ToolUtil.isOneEmpty(record, record.getId(), record.getYyjl())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        /*//根据yyjl查找手机
        String name = record.getYyjl();
//        String tel = btyArchivesMapper.getTelByName(name);
        Map<String, Object> map = new HashMap<>();
        map.put("xm", name);
        BtyArchives arch = btyArchivesMapper.getObjByCon(map);*/
        Project pro = getById(record.getId());
        String oldyyjl = pro.getYyjl();
        String name = record.getYyjl();
        String tel = record.getTel().trim();
        if(ToolUtil.isNotEmpty(oldyyjl) && oldyyjl.equals(tel)){//如果两次人相同，不再处理
//            return;
            return ResponseData.success();
        }

        Long userId;
        String userName;
        if (ToolUtil.isEmpty(record.getCreateUser())){
            userId = LoginContextHolder.getContext().getUserId();
            userName = LoginContextHolder.getContext().getUser().getName();
        }else {
            userId = record.getCreateUser();
            userName = userMapper.getName(record.getCreateUser());
        }

        Map<String, Object> wx = userService.getWxByUserid(userId);
        if (ToolUtil.isEmpty(wx)) {
            log.error("未获取到营运总监-{} 微信的openid,userid={}", userName, userId);
        }
        String yyzjopenid = (String) wx.get("openid");

        if (ToolUtil.isEmpty(record.getTel())) {
            log.error("营运经理-{}未绑定手机!", record.getYyjl());
            errwords[3] = "指定营运经理失败："+name+"-" + BusExceptionEnum.NO_PHONE.getMessage();
            JSONObject errparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), errwords[3], errwords);
            //报错时，推送给营运总监失败
            weChatSendTempMsgService.sendmsg(yyzjopenid.split(","), BusConst.MSURL, errparam);
//            throw new BusException(BusExceptionEnum.NO_PHONE);
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseData.error(2001,"此人档案不存在，请联系孙娇添加档案");
        }
        record.setYyjl(tel);
        record.setUpdateTime(new Date());
        int i = baseMapper.updateProjectByCondition(record);
        if (i > 0) {
            //保存taskstatus
            TaskStatusParam ts = new TaskStatusParam();
            ts.setProId(record.getId());
            ts.setTaskId(40);
            ts.setStatus(1);
            if (ToolUtil.isNotEmpty(record.getCreateUser())){
                ts.setCreateUser(record.getCreateUser());
            }
            int tsExist = taskStatusService.selectStau(ts);
            if (tsExist == 0){
                taskStatusService.add(ts);
            }else {
                taskStatusService.updateAuditSt(ts);
            }

            //保存flow
            TaskFlowParam flow = new TaskFlowParam();
            flow.setProId(record.getId());
            flow.setTaskId(40);
            flow.setStatus(1);
            if (ToolUtil.isNotEmpty(record.getCreateUser())){
                flow.setCreateUser(record.getCreateUser());
            }else {
                flow.setCreateUser(LoginContextHolder.getContext().getUser().getId());
            }
            taskFlowService.add(flow);
            taskStatusService.insertNextNode(ts);//插入下个节点

            //修改通讯录营运经理
            if (ToolUtil.isNotEmpty(pro.getYaoma())){
                BtyTxl btyTxl = new BtyTxl();
                btyTxl.setYytel(tel);
                btyTxl.setYyjlqy(name);
                btyTxl.setCtbh(pro.getYaoma());
                btyTxlMapper.updateTxlYy(btyTxl);
            }

            //推送营运经理通知
            String[] strs = {"消息通知", "消息通知", DateUtil.getNow(), "已指定您为该店营运经理，请指定督导"};
            JSONObject param = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), name + ",请指定督导！", strs);
            List<BtyWx> wxs = btyWxService.getWx(tel);
            //营运经理
            List<String> openidlist = getOpenids(wxs);
            if (ToolUtil.isEmpty(openidlist)) {
                log.error("{},营运经理-{}", BusExceptionEnum.NO_WX.getMessage(), name);
                errwords[3] = "指定营运经理失败：" + BusExceptionEnum.NO_WX.getMessage();
                JSONObject errparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), errwords[3], errwords);
                //报错时，推送给营运总监失败
                weChatSendTempMsgService.sendmsg(yyzjopenid.split(","), BusConst.MSURL, errparam);
//                throw new BusException(BusExceptionEnum.NO_WX);
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseData.error(2002,"查无此人，请确认手机号是否一致且已绑定部门");
            }

            String[] openids = openidlist.toArray(new String[openidlist.size()]);

            //营运经理
            List<User> user1 = btyWxMapper.getUser(openidlist);
            if (ToolUtil.isNotEmpty(user1)) {
                for (User user : user1) {
                    //指定督导
                    String syUrl = BusConst.DDURL + "&proId=" + record.getId() + "&taskId=41" + "&userId=" + user.getUserId();
                    String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                    //推送营运经理消息
                    weChatSendTempMsgService.sendmsg(openids, url, param);
                    log.info("=======营运经理已保存'通知并推送给营运经理-{}==========");

                    //消息表中新增推送指定营运经理消息
                    GcgMsg gcgMsg = new GcgMsg();
                    gcgMsg.setBusinessId(record.getId());//业务id
                    gcgMsg.setBusinessType("工程");//业务类型
                    gcgMsg.setBusinessName(pro.getName());//业务名称
                    gcgMsg.setTaskId(40);//任务id
                    gcgMsg.setMsgType("指定营运经理提醒");//消息类型
                    gcgMsg.setMessage(Arrays.toString(strs));//消息内容
                    gcgMsg.setPath(url);//跳转路径
                    gcgMsg.setTaskStatus(0);//任务状态;0->已完成，1->未完成
                    if (ToolUtil.isNotEmpty(record.getCreateUser())){
                        gcgMsg.setSendUser(record.getCreateUser());//发送人id
                    }else {
                        gcgMsg.setSendUser(LoginContextHolder.getContext().getUserId());//发送人id
                    }
                    gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                    gcgMsg.setCreateTime(new Date());//创建时间

                    //消息表新增出图日期消息
                    msgMapper.insert(gcgMsg);
                }
            }

            if(tsExist>0){
                //推送给旧的营运经理
                List<BtyWx> oldwxs = btyWxService.getWx(oldyyjl);
                List<String> oldopenidList = getOpenids(oldwxs);
                String[] oldOpenids = oldopenidList.toArray(new String[oldopenidList.size()]);
                String[] oldstrs = {"消息通知", "消息通知", DateUtil.getNow(), "由你负责的店,营运经理已变更为"+name};
                JSONObject oldparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(),  "由你负责的店,营运经理已变更为"+name, oldstrs);
                weChatSendTempMsgService.sendmsg(oldOpenids, BusConst.MSURL, oldparam);
            }
            //推送给开发人员 yyjl的信息
            Map<String, Object> kfrywx = userService.getWxByUserid(pro.getCreateUser());
            if (ToolUtil.isEmpty(kfrywx)) {
                log.error("未获取到开发人员微信的openid,userid={}", pro.getCreateUser());
//                return;
                return ResponseData.success();
            }
            String openid = (String) kfrywx.get("openid");
            String[] os = {openid};
            String[] str2 = {"消息通知", "消息通知", DateUtil.getNow(), "该工程已分派营运经理"};
            JSONObject kfryjs = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), "营运经理：" + name + ",电话：" + tel, str2);
            weChatSendTempMsgService.sendmsg(os, BusConst.MSURL, kfryjs);
            log.info("'营运经理已保存'通知并推送给{}", name);


            //刘书伟
            String[] openidsLiu = new String[]{BusConst.LSW};
            String data = pro.getName() + "已确定开店，请确认店名是否合适！";
            JSONObject tempObj = weChatSendTempMsgService.setTempParam(pro.getName(), null, "消息通知", "消息通知", DateUtil.getNow(), data);
            //推送消息
            weChatSendTempMsgService.sendmsg(openidsLiu, BusConst.MSURL, tempObj);
            log.info("=======推送收刘书伟消息==========");
        }
        return ResponseData.success();
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveGcDd(ProjectParam record) {
        if (ToolUtil.isOneEmpty(record, record.getId(), record.getDd())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        boolean isexist = isexist(record.getId(), ProjectTaskEnum.TASK_40.getCode().toString());
        if(!isexist){
            throw new ServiceException(BusExceptionEnum.ERR_NO_YYJLOK);
        }
        /*//根据dd查找手机
        String name = record.getDd();
        Map<String, Object> map = new HashMap<>();
        map.put("xm", name);
        BtyArchives arch = btyArchivesMapper.getObjByCon(map);*/
        Project pro = getById(record.getId());
        String olddd = pro.getDd();

        String name = record.getDd();
        String tel = record.getTel().trim();
        if(ToolUtil.isNotEmpty(olddd) && olddd.equals(tel)){//如果两次人相同，不再处理
            return;
        }
        if (ToolUtil.isEmpty(record.getTel())) {
            log.error("督导-{}未绑定手机!", name);
            throw new BusException(BusExceptionEnum.NO_PHONE);
        }
        record.setDd(tel);
        record.setUpdateTime(new Date());
        int i = baseMapper.updateProjectByCondition(record);
        //// TODO: 2022-06-13  
        if(i>0){
            List<BtyContractResult>gcList=btyContractMapper.gcList(record.getId());
            if(ToolUtil.isNotEmpty(gcList)&&gcList.size()>0){
                String yaoma=gcList.get(0).getYaoma();
                String dm=gcList.get(0).getName();
                String cwm=gcList.get(0).getCwm();
                String kfry=gcList.get(0).getData();
                String phone=gcList.get(1).getData();
                BtyContract contract=new BtyContract();
                if(gcList.size()==3){
                    BigDecimal area= new BigDecimal(gcList.get(2).getData()).setScale(2,BigDecimal.ROUND_HALF_UP);
                    contract.setArea(area);
                }
                contract.setDm(dm);
                contract.setYaoma(yaoma);
                contract.setCwm(cwm);
                contract.setDeveloper(kfry);
                contract.setPhone(phone);
                btyContractMapper.insert(contract);
                btyContractMapper.saveArea();
            }
        }

        if(i>0){
            List<BtyDoubleCardResult> list=doubleCardMapper.projectDoubleCardList(record.getId());
            List<BtyDoubleCard>cards=doubleCardMapper.selectList(new QueryWrapper<BtyDoubleCard>().eq("pro_id",record.getId()));
            if(cards.size()<=0) {
                if (ToolUtil.isNotEmpty(list) && list.size() > 0) {
                    for (BtyDoubleCardResult result : list) {
                        BtyDoubleCard card = new BtyDoubleCard();
                        card.setId(UUIDUtils.getId());
                        card.setGcdm(result.getGcdm());
                        card.setYaoma(result.getYaoma());
                        card.setYyjl(result.getYyjl());
                        card.setYyjlTel(result.getYyjlTel());
                        card.setDd(result.getDd());
                        card.setDdTel(result.getDdTel());
                        //根据工程id获取流程相关信息
                        List<BtyDoubleCardResult> taskList = doubleCardMapper.taskList(result.getProId());
                        if (ToolUtil.isNotEmpty(taskList) && taskList.size() > 0) {
                            for (BtyDoubleCardResult taskResult : taskList) {
                                int taskId = taskResult.getTaskId();
                                //营业执照图片
                                if (taskId == 11) {
                                    card.setBusinessLicensePic(taskResult.getContent());
                                }
                                //营业执照名称
                                if (taskId == 56) {
                                    card.setBusinessLicense(taskResult.getContent());
                                }
                                //统一社会信用代码
                                if (taskId == 57) {
                                    card.setSocialCreditCode(taskResult.getContent());
                                }
                                //营业执照地址
                                if (taskId == 55) {
                                    card.setBusinessLicenseAddress(taskResult.getContent());
                                }
                                //法人姓名
                                if (taskId == 47) {
                                    card.setFrxm(taskResult.getContent());
                                }
                                //法人身份证
                                if (taskId == 42) {
                                    card.setFrsfz(taskResult.getContent());
                                }
                                //卫生许可证
                                if (taskId == 13) {
                                    card.setFoodBusinessLicensePic(taskResult.getContent());
                                }
                                //卫生许可证年审日期
                                if (taskId == 44) {
                                    card.setFoodBusinessLicenseDate(taskResult.getContent());
                                }
                            }
                        }
                        if (ToolUtil.isNotEmpty(card.getBusinessLicensePic()) && ToolUtil.isNotEmpty(card.getFoodBusinessLicensePic())) {
                            //状态 1未提交 2待审核 3已通过 4已驳回
                            card.setStatus(2);
                        } else {
                            card.setStatus(1);
                        }
                        card.setProId(result.getProId());
                        doubleCardMapper.insert(card);
                    }
                }
            }else{
                BtyDoubleCard card=doubleCardMapper.selectOne(new QueryWrapper<BtyDoubleCard>().eq("pro_id",record.getId()));
                card.setDd(name);
                card.setDdTel(tel);
                doubleCardMapper.updateById(card);
            }

            List<BtyDoubleCardResult> list1=doubleCardMapper.projectNoDoubleCardList(record.getId());
            if(cards.size()<=0){
                if(ToolUtil.isNotEmpty(list1)&&list1.size()>0) {
                    for (BtyDoubleCardResult result : list1) {
                        BtyDoubleCard card = new BtyDoubleCard();
                        card.setId(UUIDUtils.getId());
                        card.setGcdm(result.getGcdm());
                        card.setYaoma(result.getYaoma());
                        card.setYyjl(result.getYyjl());
                        card.setYyjlTel(result.getYyjlTel());
                        card.setDd(result.getDd());
                        card.setDdTel(result.getDdTel());
                        card.setStatus(1);
                        //状态 1未提交 2待审核 3已通过 4已驳回
                        card.setProId(result.getProId());
                        doubleCardMapper.insert(card);
                    }
                }
            } else{
                BtyDoubleCard card=doubleCardMapper.selectOne(new QueryWrapper<BtyDoubleCard>().eq("pro_id",record.getId()));
                card.setDd(name);
                card.setDdTel(tel);
                doubleCardMapper.updateById(card);
            }

        }

        Long userId;
        if (ToolUtil.isNotEmpty(record.getCreateUser())){
            userId = record.getCreateUser();
        }else {
            userId = LoginContextHolder.getContext().getUser().getId();
        }

        if (i > 0) {
            //保存taskstatus
            TaskStatusParam ts = new TaskStatusParam();
            ts.setProId(record.getId());
            ts.setTaskId(ProjectTaskEnum.TASK_41.getCode());
            ts.setStatus(1);
            ts.setCreateUser(userId);
            int tsExist = taskStatusService.selectStau(ts);
            if (tsExist == 0){
                taskStatusService.add(ts);
            }else {
                taskStatusService.updateAuditSt(ts);
            }

            //保存flow
            TaskFlowParam flow = new TaskFlowParam();
            flow.setProId(record.getId());
            flow.setTaskId(ProjectTaskEnum.TASK_41.getCode());
            flow.setStatus(1);
            flow.setCreateUser(userId);
            taskFlowService.add(flow);
            taskStatusService.insertNextNode(ts);//插入下个节点

            //修改通讯录督导
            if (ToolUtil.isNotEmpty(pro.getYaoma())){
                BtyTxlRY btyTxlRY = new BtyTxlRY();
                btyTxlRY.setLxfs(tel);
                btyTxlRY.setFzr(name);
                btyTxlRY.setZw("督导");
                btyTxlRY.setSsctbh(pro.getYaoma());
                btyTxlMapper.updateTxlRYDd(btyTxlRY);
            }

            //推送督导通知
            String[] strs = {"消息通知", "消息通知", DateUtil.getNow(), "您有新的开新店任务"};
            System.out.println(Arrays.toString(strs)+"''''''''''''");
            JSONObject param = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), name + ":您有新的开新店任务！", strs);
            if(tsExist>0){
                //修改督导后推送旧督导通知
                List<BtyWx> oldwxs = btyWxService.getWx(olddd);
                List<String> oldopenidList = getOpenids(oldwxs);
                String[] oldOpenids = oldopenidList.toArray(new String[oldopenidList.size()]);
                String[] oldstrs = {"消息通知", "消息通知", DateUtil.getNow(), "由你负责的店,督导已变更为"+name};
                JSONObject oldparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(),  "由你负责的店,督导已变更为"+name, oldstrs);
                weChatSendTempMsgService.sendmsg(oldOpenids, BusConst.MSURL, oldparam);
            }

            //督导
            List<BtyWx> wxs = btyWxService.getWx(tel);
            List<String> openidlist = getOpenids(wxs);
            if (ToolUtil.isEmpty(openidlist)) {
                log.error("{},督导-{}", BusExceptionEnum.NO_WX.getMessage(), name, BusExceptionEnum.NO_WX.getCode());
                throw new BusException(BusExceptionEnum.NO_WX);
            }

            //督导id
            List<User> userList = btyWxMapper.getUser(openidlist);
            if (ToolUtil.isNotEmpty(userList)) {
                for (User user1 : userList) {

                    //查询是否开工
                    int count = taskMapper.getRent(record.getId(), 32);
                    //无开工日期
                    if (count == 0) {
                        //无开工日期提醒页面url
                        String bdUrl = BusConst.KGURL + "&proId=" + record.getId() + "&userId=" + user1.getUserId();
                        String url1 = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(bdUrl) + type + scope + state;
                        String[] openid = new String[]{user1.getOpenid()};

                        //推送消息（无开工日期提醒页面）
                        weChatSendTempMsgService.sendmsg(openid, url1, param);
                        log.info("'督导已保存'通知并推送给 {}", name);

                        //消息表中新增指定督导消息
                        GcgMsg gcgMsg2 = new GcgMsg();
                        gcgMsg2.setBusinessId(record.getId());//业务id
                        gcgMsg2.setBusinessType("工程");//业务类型
                        gcgMsg2.setBusinessName(pro.getName());//业务名称
//                    gcgMsg2.setTaskId(19);//任务id
                        gcgMsg2.setMsgType("指定督导提醒");//消息类型
                        gcgMsg2.setMessage(Arrays.toString(strs));//消息内容
                        gcgMsg2.setTaskStatus(0);//任务状态;0->已完成，1->未完成
                        if (ToolUtil.isEmpty(record.getCreateUser())){
                            gcgMsg2.setSendUser(LoginContextHolder.getContext().getUserId());//发送人id
                        }else {
                            gcgMsg2.setSendUser(record.getCreateUser());//发送人id
                        }
                        gcgMsg2.setReceiveUser(user1.getUserId());//接收人ID
                        gcgMsg2.setCreateTime(new Date());//创建时间
                        gcgMsg2.setPath(url1);//跳转路径

                        //消息表新增指定督导消息
                        msgMapper.insert(gcgMsg2);

                    } else {
                        //本店任务页面url
                        String bdUrl = BusConst.BDURL + "&proId=" + record.getId() + "&userId=" + user1.getUserId();
                        String url1 = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(bdUrl) + type + scope + state;
                        String[] openid = new String[]{user1.getOpenid()};

                        //推送消息（本店任务页面）
                        weChatSendTempMsgService.sendmsg(openid, url1, param);
                        log.info("'督导已保存'通知并推送给 {}", name);

                        //消息表中新增指定督导消息
                        GcgMsg gcgMsg2 = new GcgMsg();
                        gcgMsg2.setBusinessId(record.getId());//业务id
                        gcgMsg2.setBusinessType("工程");//业务类型
                        gcgMsg2.setBusinessName(pro.getName());//业务名称
//                    gcgMsg2.setTaskId(19);//任务id
                        gcgMsg2.setMsgType("指定督导提醒");//消息类型
                        gcgMsg2.setMessage(Arrays.toString(strs));//消息内容
                        gcgMsg2.setTaskStatus(0);//任务状态;0->已完成，1->未完成
                        if (ToolUtil.isEmpty(record.getCreateUser())){
                            gcgMsg2.setSendUser(LoginContextHolder.getContext().getUserId());//发送人id
                        }else {
                            gcgMsg2.setSendUser(record.getCreateUser());//发送人id
                        }
                        gcgMsg2.setReceiveUser(user1.getUserId());//接收人ID
                        gcgMsg2.setCreateTime(new Date());//创建时间
                        gcgMsg2.setPath(url1);//跳转路径

                        //消息表新增指定督导消息
                        msgMapper.insert(gcgMsg2);


                        //查询开工日期
                        String time = taskMapper.getCon(record.getId(), 32);
                        //刘书伟
                        String syxt = BusConst.LSW;
                        String[] openids = new String[]{syxt};
                        //收银系统负责人 (刘书伟)id
                        User user = btyWxMapper.selectUser(syxt);
                        Map<String, String> openidMap = projectService.selectDd(record.getId());
                        String ddName = openidMap.get("ddName");
                        String ddTel = openidMap.get("ddTel");
                        //推送收银系统确认消息
                        String data = pro.getName() + "已确定开工日期为:" + time + ",请确认收银系统。该店督导为：" + ddName + "电话为:" + ddTel;
                        log.info("开工日期已确认=========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(pro.getName(), null, "确认收银系统", "收银系统", DateUtil.getNow(), data);

                        if (ToolUtil.isNotEmpty(user)){
                            //收银系统url（负责人）
                            String syUrl = BusConst.SYURL + "&proId=" + record.getId() + "&taskId=21" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                            //推送收银系统消息
//                            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                            log.info("=======推送收银系统负责人消息==========");

                            //消息表中新增收银系统消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(record.getId());//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(pro.getName());//业务名称
                            gcgMsg.setTaskId(21);//任务id
                            gcgMsg.setMsgType("确认收银系统提醒");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            if (ToolUtil.isEmpty(record.getCreateUser())){
                                gcgMsg2.setSendUser(LoginContextHolder.getContext().getUserId());//发送人id
                            }else {
                                gcgMsg2.setSendUser(record.getCreateUser());//发送人id
                            }
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增收银系统数据
                            msgMapper.insert(gcgMsg);
                        }
                    }

                }
            }

        }
    }

    /**
     * 手机端
     * @param record
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData saveGcWxDd(ProjectParam record) {
        if (ToolUtil.isOneEmpty(record, record.getId(), record.getDd())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        boolean isexist = isexist(record.getId(), ProjectTaskEnum.TASK_40.getCode().toString());
        if(!isexist){
            throw new ServiceException(BusExceptionEnum.ERR_NO_YYJLOK);
        }
        /*//根据dd查找手机
        String name = record.getDd();
        Map<String, Object> map = new HashMap<>();
        map.put("xm", name);
        BtyArchives arch = btyArchivesMapper.getObjByCon(map);*/
        Project pro = getById(record.getId());
        String olddd = pro.getDd();

        String name = record.getDd();
        String tel = record.getTel().trim();
        if(ToolUtil.isNotEmpty(olddd) && olddd.equals(tel)){//如果两次人相同，不再处理
//            return;
            return ResponseData.success();
        }
        if (ToolUtil.isEmpty(record.getTel())) {
            log.error("督导-{}未绑定手机!", name);
//            throw new BusException(BusExceptionEnum.NO_PHONE);

            //事务回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return ResponseData.error(2001,"此人档案不存在，请联系孙娇添加档案");
        }
        record.setDd(tel);
        record.setUpdateTime(new Date());
        int i = baseMapper.updateProjectByCondition(record);

        Long userId;
        if (ToolUtil.isNotEmpty(record.getCreateUser())){
            userId = record.getCreateUser();
        }else {
            userId = LoginContextHolder.getContext().getUser().getId();
        }

        if (i > 0) {
            //保存taskstatus
            TaskStatusParam ts = new TaskStatusParam();
            ts.setProId(record.getId());
            ts.setTaskId(ProjectTaskEnum.TASK_41.getCode());
            ts.setStatus(1);
            ts.setCreateUser(userId);
            int tsExist = taskStatusService.selectStau(ts);
            if (tsExist == 0){
                taskStatusService.add(ts);
            }else {
                taskStatusService.updateAuditSt(ts);
            }

            //保存flow
            TaskFlowParam flow = new TaskFlowParam();
            flow.setProId(record.getId());
            flow.setTaskId(ProjectTaskEnum.TASK_41.getCode());
            flow.setStatus(1);
            flow.setCreateUser(userId);
            taskFlowService.add(flow);
            taskStatusService.insertNextNode(ts);//插入下个节点

            //修改通讯录督导
            if (ToolUtil.isNotEmpty(pro.getYaoma())){
                BtyTxlRY btyTxlRY = new BtyTxlRY();
                btyTxlRY.setLxfs(tel);
                btyTxlRY.setFzr(name);
                btyTxlRY.setZw("督导");
                btyTxlRY.setSsctbh(pro.getYaoma());
                btyTxlMapper.updateTxlRYDd(btyTxlRY);
            }

            //推送督导通知
            String[] strs = {"消息通知", "消息通知", DateUtil.getNow(), "您有新的开新店任务"};
            System.out.println(Arrays.toString(strs)+"''''''''''''");
            JSONObject param = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(), name + ":您有新的开新店任务！", strs);
            if(tsExist>0){
                //修改督导后推送旧督导通知
                List<BtyWx> oldwxs = btyWxService.getWx(olddd);
                List<String> oldopenidList = getOpenids(oldwxs);
                String[] oldOpenids = oldopenidList.toArray(new String[oldopenidList.size()]);
                String[] oldstrs = {"消息通知", "消息通知", DateUtil.getNow(), "由你负责的店,督导已变更为"+name};
                JSONObject oldparam = weChatSendTempMsgService.setTempParam(record.getId() + "." + pro.getName(),  "由你负责的店,督导已变更为"+name, oldstrs);
                weChatSendTempMsgService.sendmsg(oldOpenids, BusConst.MSURL, oldparam);
            }

            //督导
            List<BtyWx> wxs = btyWxService.getWx(tel);
            List<String> openidlist = getOpenids(wxs);
            if (ToolUtil.isEmpty(openidlist)) {
                log.error("{},督导-{}", BusExceptionEnum.NO_WX.getMessage(), name, BusExceptionEnum.NO_WX.getCode());
//                throw new BusException(BusExceptionEnum.NO_WX);
                //事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseData.error(2002,"查无此人，请确认手机号是否一致且已绑定部门");
            }

            //督导id
            List<User> userList = btyWxMapper.getUser(openidlist);
            if (ToolUtil.isNotEmpty(userList)) {
                for (User user1 : userList) {

                    //查询是否开工
                    int count = taskMapper.getRent(record.getId(), 32);
                    //无开工日期
                    if (count == 0) {
                        //无开工日期提醒页面url
                        String bdUrl = BusConst.KGURL + "&proId=" + record.getId() + "&userId=" + user1.getUserId();
                        String url1 = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(bdUrl) + type + scope + state;
                        String[] openid = new String[]{user1.getOpenid()};

                        //推送消息（无开工日期提醒页面）
                        weChatSendTempMsgService.sendmsg(openid, url1, param);
                        log.info("'督导已保存'通知并推送给 {}", name);

                        //消息表中新增指定督导消息
                        GcgMsg gcgMsg2 = new GcgMsg();
                        gcgMsg2.setBusinessId(record.getId());//业务id
                        gcgMsg2.setBusinessType("工程");//业务类型
                        gcgMsg2.setBusinessName(pro.getName());//业务名称
//                    gcgMsg2.setTaskId(19);//任务id
                        gcgMsg2.setMsgType("指定督导提醒");//消息类型
                        gcgMsg2.setMessage(Arrays.toString(strs));//消息内容
                        gcgMsg2.setTaskStatus(0);//任务状态;0->已完成，1->未完成
                        if (ToolUtil.isEmpty(record.getCreateUser())){
                            gcgMsg2.setSendUser(LoginContextHolder.getContext().getUserId());//发送人id
                        }else {
                            gcgMsg2.setSendUser(record.getCreateUser());//发送人id
                        }
                        gcgMsg2.setReceiveUser(user1.getUserId());//接收人ID
                        gcgMsg2.setCreateTime(new Date());//创建时间
                        gcgMsg2.setPath(url1);//跳转路径

                        //消息表新增指定督导消息
                        msgMapper.insert(gcgMsg2);

                    } else {
                        //本店任务页面url
                        String bdUrl = BusConst.BDURL + "&proId=" + record.getId() + "&userId=" + user1.getUserId();
                        String url1 = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(bdUrl) + type + scope + state;
                        String[] openid = new String[]{user1.getOpenid()};

                        //推送消息（本店任务页面）
                        weChatSendTempMsgService.sendmsg(openid, url1, param);
                        log.info("'督导已保存'通知并推送给 {}", name);

                        //消息表中新增指定督导消息
                        GcgMsg gcgMsg2 = new GcgMsg();
                        gcgMsg2.setBusinessId(record.getId());//业务id
                        gcgMsg2.setBusinessType("工程");//业务类型
                        gcgMsg2.setBusinessName(pro.getName());//业务名称
//                    gcgMsg2.setTaskId(19);//任务id
                        gcgMsg2.setMsgType("指定督导提醒");//消息类型
                        gcgMsg2.setMessage(Arrays.toString(strs));//消息内容
                        gcgMsg2.setTaskStatus(0);//任务状态;0->已完成，1->未完成
                        if (ToolUtil.isEmpty(record.getCreateUser())){
                            gcgMsg2.setSendUser(LoginContextHolder.getContext().getUserId());//发送人id
                        }else {
                            gcgMsg2.setSendUser(record.getCreateUser());//发送人id
                        }
                        gcgMsg2.setReceiveUser(user1.getUserId());//接收人ID
                        gcgMsg2.setCreateTime(new Date());//创建时间
                        gcgMsg2.setPath(url1);//跳转路径

                        //消息表新增指定督导消息
                        msgMapper.insert(gcgMsg2);


                        //查询开工日期
                        String time = taskMapper.getCon(record.getId(), 32);
                        //刘书伟
                        String syxt = BusConst.LSW;
                        String[] openids = new String[]{syxt};
                        //收银系统负责人 (刘书伟)id
                        User user = btyWxMapper.selectUser(syxt);
                        Map<String, String> openidMap = projectService.selectDd(record.getId());
                        String ddName = openidMap.get("ddName");
                        String ddTel = openidMap.get("ddTel");
                        //推送收银系统确认消息
                        String data = pro.getName() + "已确定开工日期为:" + time + ",请确认收银系统。该店督导为：" + ddName + "电话为:" + ddTel;
                        log.info("开工日期已确认=========");

                        JSONObject tempObj = weChatSendTempMsgService.setTempParam(pro.getName(), null, "确认收银系统", "收银系统", DateUtil.getNow(), data);

                        if (ToolUtil.isNotEmpty(user)){
                            //收银系统url（负责人）
                            String syUrl = BusConst.SYURL + "&proId=" + record.getId() + "&taskId=21" + "&userId=" + user.getUserId();
                            String url = path + gzhConfig.getAppid() + "&redirect_uri=" + URLEncoder.encode(syUrl) + type + scope + state;

                            //推送收银系统消息
//                            weChatSendTempMsgService.sendmsg(openids, BusConst.MSURL, tempObj);
                            weChatSendTempMsgService.sendmsg(openids, url, tempObj);
                            log.info("=======推送收银系统负责人消息==========");

                            //消息表中新增收银系统消息
                            GcgMsg gcgMsg = new GcgMsg();
                            gcgMsg.setBusinessId(record.getId());//业务id
                            gcgMsg.setBusinessType("工程");//业务类型
                            gcgMsg.setBusinessName(pro.getName());//业务名称
                            gcgMsg.setTaskId(21);//任务id
                            gcgMsg.setMsgType("确认收银系统提醒");//消息类型
                            gcgMsg.setMessage(data);//消息内容
                            gcgMsg.setPath(url);//跳转路径
                            gcgMsg.setTaskStatus(1);//任务状态;0->已完成，1->未完成
                            if (ToolUtil.isEmpty(record.getCreateUser())){
                                gcgMsg2.setSendUser(LoginContextHolder.getContext().getUserId());//发送人id
                            }else {
                                gcgMsg2.setSendUser(record.getCreateUser());//发送人id
                            }
                            gcgMsg.setReceiveUser(user.getUserId());//接收人ID
                            gcgMsg.setCreateTime(new Date());//创建时间

                            //消息表新增收银系统数据
                            msgMapper.insert(gcgMsg);
                        }
                    }

                }
            }

        }
        return ResponseData.success();
    }

    /**
     * 获取opendis[]
     * @param wxs
     * @return
     */
    private List<String> getOpenids(List<BtyWx> wxs) {
        List<String> list = new ArrayList<>();
        for (BtyWx wx : wxs) {
            if (ToolUtil.isNotEmpty(wx.getOpenid())) {
                list.add(wx.getOpenid());
            }
        }
        return list;
    }

    /**
     * 查询微信推送督导及营运经理
     *
     * @return
     */
    @Override
    public Map<String, String> selectDd(Integer proid) {
        Project project = projectMapper.selectDd(proid);
        //督导openid
        String dd = project.getDdOpenid();
        String ddTel = project.getDdTel();
        String ddName = project.getDdName();
        //营运经理openid
        String yyjl = project.getYyjlOpenid();
        String yyTel = project.getYyjlTel();
        String yyName = project.getYyjlName();

        Map<String, String> map = new HashMap<>();
        map.put("dd", dd);
        map.put("yyjl", yyjl);
        map.put("ddTel", ddTel);
        map.put("yyTel", yyTel);
        map.put("ddName", ddName);
        map.put("yyName", yyName);
        return map;
    }

    /**
     * 查询督导列表
     */
    @Override
    public List<Map> selectDdList(String phone) {
//        //查询营运经理姓名
//        String name = projectMapper.selectName(phone);
//        //查询该营运经理对应的督导
//        List<Map> ddList = projectMapper.selectDdList(name);
        List<Map> ddList = projectMapper.selectDdList(phone);
        return ddList;
    }

    /**
     * 查询营运经理列表
     *
     * @return
     */
    @Override
    public List<Map> selectYyjlList() {
        return projectMapper.selectYyjlList();
    }

    /**
     * 查询表格内容列表
     *
     * @return
     */
    @Override
    public List<MouldBoardMsg> selectMsgList(Integer proId, Integer mouldId) {
        return projectMapper.selectMsgList(proId, mouldId);
    }

    /**
     * 工程完工
     *
     * @param proId
     * @return
     */
    @Override
    public ResponseData getStatus(Integer proId) {
        //修改状态,所有修改操作数据库新增条数必须都大于0才会提交事务
        StringBuilder result = new StringBuilder();
        // 数据库修改条数
        int count = 0;

        Integer pro = projectMapper.getStatus(proId);
        Integer task = projectMapper.getTask();
        //工程已完工
        if (pro.equals(task)) {

            //流程状态表
            TaskStatus taskStatus = new TaskStatus();
            //督导确认完工
            taskStatus.setTaskId(39);
            taskStatus.setProId(proId);
            taskStatus.setStatus(1);
            taskStatus.setTaskName("督导确认完工");

            //新增
            count = taskMapper.addRent(taskStatus);
            result.append(count > 0 ? 1 : 0);

            //流程明细表
            TaskFlow taskFlow = new TaskFlow();
            taskFlow.setProId(proId);
            taskFlow.setTaskId(39);
            taskFlow.setStatus(1);//1提交；2审核未通过；3审核通过
            taskFlow.setTaskName("督导确认完工");
            taskFlow.setCreateUser(LoginContextHolder.getContext().getUserId());
            taskFlow.setCreateTime(new Date());
            //新增流程明细表
            count = taskFlowMapper.add(taskFlow);
            result.append(count > 0 ? 1 : 0);

            if (result.indexOf("0") >= 0) {
                //事务回滚
                TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                return ResponseData.error("添加失败");
            }
            return ResponseData.success();
        }
        return ResponseData.success("工程未完工");
    }

    @Override
    public LayuiPageInfo getAllProPageWithTaskFlow(ProjectParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getAllProPage(pageContext, param);
        //所有的工程
        List<ProjectResult> projectResultList = page.getRecords();
        TaskFlowParam taskFlowParam = new TaskFlowParam();
        Map<String, List<TaskFlowResult>> proTaskFolwMap = new HashMap<>();

        if (CollectionUtil.isNotEmpty(projectResultList)) {
            //所有的工程任务流水
            List<TaskFlowResult> taskFlowResults = taskFlowMapper.proTaskFolwList(taskFlowParam);
            if (CollectionUtil.isNotEmpty(taskFlowResults)) {
                for (ProjectResult projectResult : projectResultList) {
                    List<TaskFlowResult> taskFlowList = new LinkedList<>();
                    for (TaskFlowResult taskFlowResult : taskFlowResults) {
                        if (taskFlowResult.getProId()!=null && taskFlowResult.getProId().equals(projectResult.getId())) {
                            taskFlowList.add(taskFlowResult);
                        }
                    }
                    if (CollectionUtil.isNotEmpty(taskFlowList)) {
                        proTaskFolwMap.put(projectResult.getName(), taskFlowList);
                    }
                }
            }
            //放入工程任务流水
            for (ProjectResult projectResult : projectResultList) {
                projectResult.setTaskFlowResultList(changeLocal(proTaskFolwMap.get(projectResult.getName())));
            }
        }
        return LayuiPageFactory.createPageInfo(page);
    }


    //调换位置
    private List<TaskFlowResult> changeLocal(List<TaskFlowResult> taskFlowResultList){
        Integer index1=null;
        Integer index2=null;
        if(CollectionUtil.isNotEmpty(taskFlowResultList)){
            for (int i=0;i<taskFlowResultList.size();i++) {
                TaskFlowResult taskFlowResult=taskFlowResultList.get(i);
                if (taskFlowResult.getTaskId()==5) {
                    index1=i;
                }
                if (taskFlowResult.getTaskId()==6) {
                    index2=i;
                }
            }
        }
        if(index1!=null&&index2!=null){
            Collections.swap(taskFlowResultList,index1,index2);
        }

        return taskFlowResultList;
    }



    @Override
    public LayuiPageInfo getAllProject(ProjectParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.getAllProPage(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<Map<String, Object>> customMapList(ProjectParam param) {
        //工程门店
        List<Map<String, Object>> maps = new ArrayList<>();
        if (param.getUseType() != null && param.getUseType().equals(UseEnum.ADD.getCode())) {
            //添加时-已经存在门店装修表中的门店不显示在门店选择select中
            maps = this.baseMapper.customMapMdzxList(param);
        } else if (param.getUseType() != null && param.getUseType().equals(UseEnum.EDIT.getCode())) {
            //修改时-已经存在门店装修表中的门店不显示在门店选择select中
            maps = this.baseMapper.customMapMdzxList(param);
        } else {
            maps = this.baseMapper.customMapList(param);
        }
        return maps;
    }

    /**
     * 批量隐藏接口
     *
     * @param id
     * @param status
     */
    @Override
    public int editBatch(String id, Integer status) {
        return projectMapper.editBatch(id, status);
    }

    @Override
    public ProjectResult selectOneByParam(ProjectParam projectParam) {
        return projectMapper.selectOneByParam(projectParam);
    }

    @Override
    public LayuiPageInfo projectList(ProjectParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.projectList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }


    @Override
    public int getName(String name) {
        return projectMapper.getName(name);
    }

    @Override
    public LayuiPageInfo jindu(ProjectParam param) {
        Page page = getPageContext();
        IPage<ProjectJdResult> list = projectMapper.jindu(page, param);
        return LayuiPageFactory.createPageInfo(list);
    }

    @Override
    public LayuiPageInfo cokeReportList(ProjectParam param) {
        if (ToolUtil.isNotEmpty(param.getTimeLimit())) {
            String[] split = param.getTimeLimit().split(" - ");
            param.setBeginTime(split[0]+" 00:00:00");
            String  endTime = split[1] + " 23:59:59";
            param.setEndTime(endTime);
        }
        Page page = getPageContext();
        IPage<ProjectJdResult> list = projectMapper.cokeReportList(page, param);
        return LayuiPageFactory.createPageInfo(list);
    }

    @Override
    public ResponseEntity<byte[]> jinduExport(HttpServletRequest request, HttpServletResponse response, ProjectParam param) {
        try {
            //要导出的数据内容
            List<ProjectJdResult> datas = this.projectMapper.jindu(param);
            BaseFrontController baseFrontController = new BaseFrontController();
            //文件名称
            String shopName = "工程进度";
            return baseFrontController.buildResponseEntity(export(datas, shopName), shopName + ".xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private InputStream export(List<ProjectJdResult> list, String shopName) {
        log.info(">>>>>>>>>>>>>>>>>>>>开始进入导出方法>>>>>>>>>>");
        ByteArrayOutputStream output = null;
        InputStream inputStream = null;
        // 保留1000条数据在内存中
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式,cell样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);

        // 报表体样式
        CellStyle cellStyle = ExcelFormatUtil.contentStyle(wb);

        //每一列字段名
        String[] titles = new String[]{"工程名称","开发人员", "营运经理", "督导", "出图日期", "开工时间", "预计完工时间", "实际完工时间", "预计开业时间", "实际开业时间","状态"};

        // 字段名所在表格的宽度，数量应与列字段名数量一致
        int[] ints = new int[]{6000, 3000,3000, 3000, 4000, 4000, 4000, 4000, 4000, 4000, 3000};
        //设置总标题内容，没有可略过
        //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
        int firstRow = 1;
        int lastRow = 1;
        int firstCol = 1;
        int lastCol = 11;
        SXSSFRow row1 = sheet.createRow(0);
        row1.setHeight((short) 600);
        SXSSFCell cell0 = row1.createCell(0);
        CellRangeAddress regionFist = new CellRangeAddress(firstRow - 1, lastRow - 1, firstCol - 1, lastCol - 1);
        sheet.addMergedRegion(regionFist);
        //设置每一列的字段名
        cell0.setCellValue(shopName);
        cell0.setCellStyle(ExcelFormatUtil.titleSytle(wb));

        //设置内容标题
        //内容的标题所在行
        int concentitleStartRow = 2;
        //设置表头样式
        ExcelFormatUtil.initContentTitleEX(sheet, header, concentitleStartRow, titles, ints);
        log.info(">>>>>>>>>>>>>>>>>>>>表头样式设置完成>>>>>>>>>>");

        //从第contentStartRow行开始为内容数据
        int contentStartRow = 3;
        if (list != null && list.size() > 0) {
            log.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");
            for (int i = 0; i < list.size(); i++) {
                ProjectJdResult result = list.get(i);

                SXSSFRow row = sheet.createRow(contentStartRow + i - 1);
                int j = 0;

                //name
                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(result.getName());
                cell.setCellStyle(cellStyle);

                //KFRY
                cell = row.createCell(j++);
                cell.setCellValue(result.getKfName());
                cell.setCellStyle(cellStyle);

                //yyjl
                cell = row.createCell(j++);
                cell.setCellValue(result.getYyjlName());
                cell.setCellStyle(cellStyle);

                //dd
                cell = row.createCell(j++);
                cell.setCellValue(result.getDdName());
                cell.setCellStyle(cellStyle);

                //出图日期
                cell = row.createCell(j++);
                cell.setCellValue(result.getCtriqi());
                cell.setCellStyle(cellStyle);

                //开工时间
                cell = row.createCell(j++);
                cell.setCellValue(result.getKgriqi());
                cell.setCellStyle(cellStyle);

                //预计完工时间
                cell = row.createCell(j++);
                cell.setCellValue(result.getJdriqi());
                cell.setCellStyle(cellStyle);

                //实际完工时间
                cell = row.createCell(j++);
                cell.setCellValue(result.getWgriqi());
                cell.setCellStyle(cellStyle);

                //预计开业时间
                cell = row.createCell(j++);
                cell.setCellValue(result.getYjkyriqi());
                cell.setCellStyle(cellStyle);

                //实际开业时间
                cell = row.createCell(j++);
                String date="";
                if(ToolUtil.isNotEmpty(result.getKyriqi())){
                    date=result.getKyriqi().substring(0,10);
                }
                cell.setCellValue(date);
                cell.setCellStyle(cellStyle);

                //status
                cell = row.createCell(j++);
                String status = result.getStatus();
                cell.setCellValue(BusConst.JINDUMAP.get(status));
                cell.setCellStyle(cellStyle);
            }
            log.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
        }

        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (output != null) {
                    output.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return inputStream;
    }

    @Override
    public List<Area> getAreaByType() {
        return this.projectMapper.getAreaByType();
    }

    /**
     * 收银系统报表
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo sYList(ProjectParam param) {
        Page page = getPageContext();
        if (ToolUtil.isNotEmpty(param.getStatus()) && param.getStatus() == 0){
            param.setStatus(null);
        }
        IPage<ProjectJdResult> list = projectMapper.sYList(page, param);
        return LayuiPageFactory.createPageInfo(list);
    }

    @Override
    public LayuiPageInfo wsjdReportList(ProjectParam param) {
        Page page = getPageContext();
        IPage<ProjectResult> list = projectMapper.wsjdReportList(page, param);
        return LayuiPageFactory.createPageInfo(list);
    }

    @Override
    public List<Map> selectDdListAll() {
        List<Map> ddList = projectMapper.selectDdListAll();
        return ddList;
    }

    @Override
    public List<Map> selectDzListAll() {
        List<Map> dzList = projectMapper.selectDzListAll();
        return dzList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData addFinishItem(ProjectParam param) {
        if(ToolUtil.isEmpty(param.getName())){
            return ResponseData.error("工程名字不能为空");
        }
        QueryWrapper<Project> q=new QueryWrapper<Project>();
        q.eq("name", param.getName());
        if(ToolUtil.isNotEmpty(param.getId())){
            q.ne("id",param.getId());
        }

        Project project = projectService.getOne(q);
        if (ToolUtil.isNotEmpty(project)) {
            return ResponseData.error("工程名称不能重复");
        }
        if(ToolUtil.isEmpty(param.getId())){
            //拼接工程名称
            param.setStatus(BusConst.PASS);
            param.setType(BusConst.GC_TYPE_HAND);
            param.setCreateUser(LoginContextHolder.getContext().getUserId());
            Project entity = getEntity(param);
            this.save(entity);
            //更新 taskFlow
            TaskFlowParam taskFlowParam = new TaskFlowParam();
            taskFlowParam.setProId(entity.getId());
            //创建店名对应的taskId   1-店名
            taskFlowParam.setTaskId(ProjectTaskEnum.TASK_1.getCode());
            //1提交；2审核未通过；3审核通过
            taskFlowParam.setStatus(BusConst.PASS);
            taskFlowParam.setTaskName(ProjectTaskEnum.TASK_1.getMessage());
            taskFlowService.add(taskFlowParam);

            //更新 taskStatus
            TaskStatusParam taskStatusParam = new TaskStatusParam();
            taskStatusParam.setProId(entity.getId());
            //创建店名对应的taskId   1-店名
            taskStatusParam.setTaskId(ProjectTaskEnum.TASK_1.getCode());
            //1提交；2审核未通过；3审核通过
            taskStatusParam.setStatus(1);
            taskStatusService.add(taskStatusParam);
        }else{
            Project oldEntity = getById(param.getId());
            Project newEntity = getEntity(param);
            ToolUtil.copyProperties(newEntity, oldEntity);
            newEntity.setUpdateUser(LoginContextHolder.getContext().getUserId());
            this.updateById(newEntity);
        }


        return ResponseData.success();
    }

    /**
     * 添加山西门店
     * @param param
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseData addFinishSx(ProjectParam param) {
        if(ToolUtil.isEmpty(param.getName())){
            return ResponseData.error("工程名字不能为空");
        }
        QueryWrapper<Project> q=new QueryWrapper<Project>();
        q.eq("name", param.getName());
        if(ToolUtil.isNotEmpty(param.getId())){
            q.ne("id",param.getId());
        }

        Project project = projectService.getOne(q);
        if (ToolUtil.isNotEmpty(project)) {
            return ResponseData.error("工程名称不能重复");
        }
        if(ToolUtil.isEmpty(param.getId())){
            //拼接工程名称
            param.setStatus(BusConst.PASS);
            param.setType(BusConst.GC_TYPE_HAND);
            param.setCreateUser(LoginContextHolder.getContext().getUserId());
            Project entity = getEntity(param);
            this.save(entity);
            //更新 taskFlow
            TaskFlowParam taskFlowParam = new TaskFlowParam();
            taskFlowParam.setProId(entity.getId());
            //创建店名对应的taskId   1-店名
            taskFlowParam.setTaskId(ProjectTaskEnum.TASK_1.getCode());
            //1提交；2审核未通过；3审核通过
            taskFlowParam.setStatus(BusConst.PASS);
            taskFlowParam.setTaskName(ProjectTaskEnum.TASK_1.getMessage());
            taskFlowService.add(taskFlowParam);

            //更新 taskStatus
            TaskStatusParam taskStatusParam = new TaskStatusParam();
            taskStatusParam.setProId(entity.getId());
            //创建店名对应的taskId   1-店名
            taskStatusParam.setTaskId(ProjectTaskEnum.TASK_1.getCode());
            //1提交；2审核未通过；3审核通过
            taskStatusParam.setStatus(1);
            taskStatusService.add(taskStatusParam);
        }else{
            Project oldEntity = getById(param.getId());
            Project newEntity = getEntity(param);
            ToolUtil.copyProperties(newEntity, oldEntity);
            newEntity.setUpdateUser(LoginContextHolder.getContext().getUserId());
            this.updateById(newEntity);
        }

        //外卖通讯录中新增数据
        BtyWmtxl btyWmtxl = new BtyWmtxl();
        btyWmtxl.setYaoma(param.getYaoma());
        if (!param.getYyName().equals("选择营运经理")){
            btyWmtxl.setYyjl(param.getYyName());
        }
        btyWmtxl.setDm(param.getName());
        btyWmtxl.setTiancai(param.getName());

        int con = 0;
        if (ToolUtil.isNotEmpty(param.getYaoma())){
            //判断BtyWmtxl中是否存在该数据
            con = btyWmtxlMapper.getYaoma(btyWmtxl);
        }else {
            con = btyWmtxlMapper.getDm(btyWmtxl);
        }

        if (con == 0){
            btyWmtxl.setStatus(1);//状态：0->导入，1->添加（导入的不可修改）
            btyWmtxlService.save(btyWmtxl);
        }else {

            int sta = 0;
            if (ToolUtil.isNotEmpty(param.getYaoma())){
                //查询该店状态
                sta = btyWmtxlMapper.getSta(btyWmtxl);
                if (sta == 1){
                    btyWmtxlMapper.updateWm(btyWmtxl);
                }
            }else {
                //查询该店状态
                sta = btyWmtxlMapper.getStaByDm(btyWmtxl);
                if (sta == 1){
                    btyWmtxlMapper.updateWmDm(btyWmtxl);
                }
            }

        }

        return ResponseData.success();
    }

    @Override
    public LayuiPageInfo listFinish(ProjectParam param) throws ParseException {
//        param.setCreateUser(LoginContextHolder.getContext().getUserId());
        Page pageContext = getPageContext();
        List<Map> maps = teamService.selectYyjlList();
        Map<Object, Object> yyjlmap = maps.stream().collect(Collectors.toMap(s -> s.get("tel"), s -> s.get("yyjl")));
        List<Map> maps2 = teamService.selectDdListAll();
        Map<Object, Object> ddmap = maps2.stream().collect(Collectors.toMap(s -> s.get("tel"), s -> s.get("dd")));
        IPage page = this.baseMapper.customPageListFinish(pageContext, param);
        for(Object rs:page.getRecords()){
            ProjectResult pr = (ProjectResult)rs;
            pr.setYyjlname(String.valueOf(yyjlmap.get(pr.getYyjl())==null?"":yyjlmap.get(pr.getYyjl())));
            pr.setDdname(String.valueOf(ddmap.get(pr.getDd())==null?"":ddmap.get(pr.getDd())));
        }
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public ResponseEntity<byte[]> areaSummaryExport(HttpServletRequest request, HttpServletResponse response, ProjectParam param) {
        try {
            //要导出的数据内容
            IPage page = this.baseMapper.projectList(new Page(1,9999), param);
            List<ProjectResult> records = page.getRecords();
            BaseFrontController baseFrontController = new BaseFrontController();
            //文件名称
            String shopName = "工程按地区统计";
            return baseFrontController.buildResponseEntity(areaSummaryHand(records, shopName), shopName + ".xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private InputStream areaSummaryHand(List<ProjectResult> list, String shopName) {
        log.info(">>>>>>>>>>>>>>>>>>>>开始进入导出方法>>>>>>>>>>");
        ByteArrayOutputStream output = null;
        InputStream inputStream = null;
        // 保留1000条数据在内存中
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式,cell样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);

        // 报表体样式
        CellStyle cellStyle = ExcelFormatUtil.contentStyle(wb);


        //每一列字段名
        List<String> nameList=new ArrayList<>(list.size()+1);
        nameList.add("序号");
        int maxNum = 0;
        int colwith=5000;
        int[] ints=new int[list.size()+1];
        for(int i=0;i<list.size();i++){
            ProjectResult rs = list.get(i);
            nameList.add(rs.getProvinceName());
            ints[i]= (i==0?2000:colwith);
            maxNum = rs.getNum()>maxNum?rs.getNum():maxNum;
        }
        ints[list.size()]=colwith;
        String[] titles = nameList.toArray(new String[nameList.size()]);
        // 字段名所在表格的宽度，数量应与列字段名数量一致

        //设置总标题内容，没有可略过
        //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
        int firstRow = 1;
        int lastRow = 1;
        int firstCol = 1;
        int lastCol = list.size()+1;
        SXSSFRow row1 = sheet.createRow(0);
        row1.setHeight((short) 600);
        SXSSFCell cell0 = row1.createCell(0);
        CellRangeAddress regionFist = new CellRangeAddress(firstRow - 1, lastRow - 1, firstCol - 1, lastCol - 1);
        sheet.addMergedRegion(regionFist);
        //设置每一列的字段名
        cell0.setCellValue(shopName);
        cell0.setCellStyle(ExcelFormatUtil.titleSytle(wb));

        //设置内容标题
        //内容的标题所在行
        int concentitleStartRow = 2;
        //设置表头样式
        ExcelFormatUtil.initContentTitleEX(sheet, header, concentitleStartRow, titles, ints);
        log.info(">>>>>>>>>>>>>>>>>>>>表头样式设置完成>>>>>>>>>>");

        //从第contentStartRow行开始为内容数据
        int contentStartRow = 3;
        if (maxNum > 0) {
            log.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");
            for (int rowIndex = 0; rowIndex < maxNum; rowIndex++) {
                SXSSFRow row = sheet.createRow(contentStartRow + rowIndex - 1);
                //xuhao
                SXSSFCell cell = row.createCell(0);
                cell.setCellValue(rowIndex+1);
                cell.setCellStyle(cellStyle);
                for (int i = 0; i < list.size(); i++) {
                    ProjectResult result = list.get(i);
                    String names = result.getName();
                    String[] nameAry = names.split("[|]");
                    //dm
                    cell = row.createCell(1+i);
                    cell.setCellValue(nameAry.length>rowIndex?nameAry[rowIndex]:"");
                    cell.setCellStyle(cellStyle);
                }
            }
            log.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
        }

        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (output != null) {
                    output.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return inputStream;
    }


    /**
     * 生成妖码
     * @param id
     */
    @Override
    public void setYaoma(Integer id){
        try {
            if(ToolUtil.isEmpty(id)){
                log.error(BusExceptionEnum.ERR_MISS_PARAM.getMessage());
                return;
            }
            Project project = getById(id);
            Integer provinceId = project.getProvinceId();
            Integer cityId = project.getCityId();
            if(ToolUtil.isOneEmpty(provinceId,cityId)){
                log.error(BusExceptionEnum.ERR_SETYAOMA.getMessage());
                return;
            }
            List<Area> areaList = new ArrayList<>();
            Area city = areaService.getById(cityId);
            Area province = areaService.getById(provinceId);

            String cityYaoma = city.getYaomaCode();
            int num=ToolUtil.isNotEmpty(city.getNum())?city.getNum():0;
            boolean frog=false;
            boolean zhixiashi=false;//是否直辖市
            if("2,19,3219,3220,3213,3214".indexOf(String.valueOf(provinceId))>=0){//北京天津重庆上海、香港澳门
                num=ToolUtil.isNotEmpty(province.getNum())?province.getNum():0;
                cityYaoma="01";
                zhixiashi=true;
            }else{
                if(ToolUtil.isEmpty(cityYaoma)){
                    AreaParam ap=new AreaParam();
                    ap.setPid(city.getPid());
                    List<Area> citylist = areaService.listMendianArea(ap);
                    int n=citylist.size()+1;
                    cityYaoma=(n<10?("0"+n):String.valueOf(n));
                    city.setYaomaCode(cityYaoma);
                    areaList.add(city);
                    frog=true;
                    num=0;
                }
            }

            String provinceYaoma = province.getYaomaCode();
            if(ToolUtil.isEmpty(provinceYaoma)){
                AreaParam ap=new AreaParam();
                ap.setPid(province.getPid());
                List<Area> provincelist = areaService.listMendianArea(ap);
                int n=provincelist.size()+1;
                provinceYaoma=(n<10?("0"+n):String.valueOf(n));
                province.setYaomaCode(provinceYaoma);
                areaList.add(province);
            }
            num++;
            if(zhixiashi){
                province.setNum(num);
                areaList.add(province);
            }else{
                city.setNum(num);
                if(!frog){
                    areaList.add(city);
                }
            }
            if(areaList.size()>0){
                for(Area a:areaList){
                    areaService.updateById(a);
                }
            }

            String xn="";
            if(num<10){
                xn="00"+num;
            }else if(num<100){
                xn="0"+num;
            }else{
                xn=String.valueOf(num);
            }

            String yaoma= provinceYaoma+cityYaoma+xn;
            project.setYaoma(yaoma);
            projectService.updateById(project);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public LayuiPageInfo yaomaList(ProjectParam param) {
        Page page = getPageContext();
        IPage<ProjectYaomaResult> list = projectMapper.yaomaList(page, param);
        return LayuiPageFactory.createPageInfo(list);
    }

    @Override
    public ResponseEntity<byte[]> yaomaListExport(HttpServletRequest request, HttpServletResponse response, ProjectParam param) {
        try {
            //要导出的数据内容
            IPage page = this.baseMapper.yaomaList(new Page(1,9999), param);
            List<ProjectYaomaResult> records = page.getRecords();
            BaseFrontController baseFrontController = new BaseFrontController();
            //文件名称
            String shopName = "工程妖码";
            return baseFrontController.buildResponseEntity(yaomaListHand(records, shopName), shopName + ".xls");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private InputStream yaomaListHand(List<ProjectYaomaResult> list, String shopName) {
        log.info(">>>>>>>>>>>>>>>>>>>>开始进入导出方法>>>>>>>>>>");
        ByteArrayOutputStream output = null;
        InputStream inputStream = null;
        // 保留1000条数据在内存中
        SXSSFWorkbook wb = new SXSSFWorkbook(1000);
        SXSSFSheet sheet = wb.createSheet();
        // 设置报表头样式,cell样式
        CellStyle header = ExcelFormatUtil.headSytle(wb);

        // 报表体样式
        CellStyle cellStyle = ExcelFormatUtil.contentStyle(wb);

        //每一列字段名
        String[] titles = new String[]{"序号","省", "市/区", "店名", "门店编码"};

        // 字段名所在表格的宽度，数量应与列字段名数量一致
        int[] ints = new int[]{2000,3000, 3000, 8000, 3000};
        //设置总标题内容，没有可略过
        //设置第一行标题：指定 4 个参数，起始行，结束行，起始列，结束列,
        int firstRow = 1;
        int lastRow = 1;
        int firstCol = 1;
        int lastCol = 5;
        SXSSFRow row1 = sheet.createRow(0);
        row1.setHeight((short) 600);
        SXSSFCell cell0 = row1.createCell(0);
        CellRangeAddress regionFist = new CellRangeAddress(firstRow - 1, lastRow - 1, firstCol - 1, lastCol - 1);
        sheet.addMergedRegion(regionFist);
        //设置每一列的字段名
        cell0.setCellValue(shopName);
        cell0.setCellStyle(ExcelFormatUtil.titleSytle(wb));

        //设置内容标题
        //内容的标题所在行
        int concentitleStartRow = 2;
        //设置表头样式
        ExcelFormatUtil.initContentTitleEX(sheet, header, concentitleStartRow, titles, ints);
        log.info(">>>>>>>>>>>>>>>>>>>>表头样式设置完成>>>>>>>>>>");

        //从第contentStartRow行开始为内容数据
        int contentStartRow = 3;
        if (list != null && list.size() > 0) {
            log.info(">>>>>>>>>>>>>>>>>>>>开始遍历数据组装单元格内容>>>>>>>>>>");
            for (int i = 0; i < list.size(); i++) {
                ProjectYaomaResult result = list.get(i);

                SXSSFRow row = sheet.createRow(contentStartRow + i - 1);
                int j = 0;

                //name
                SXSSFCell cell = row.createCell(j++);
                cell.setCellValue(i+1);
                cell.setCellStyle(cellStyle);

                cell = row.createCell(j++);
                cell.setCellValue(result.getProvinceName());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(j++);
                cell.setCellValue(result.getCityName());
                cell.setCellStyle(cellStyle);
                //name
                cell = row.createCell(j++);
                cell.setCellValue(result.getName());
                cell.setCellStyle(cellStyle);

                cell = row.createCell(j++);
                cell.setCellValue(result.getYaoma());
                cell.setCellStyle(cellStyle);
            }
            log.info(">>>>>>>>>>>>>>>>>>>>结束遍历数据组装单元格内容>>>>>>>>>>");
        }

        try {
            output = new ByteArrayOutputStream();
            wb.write(output);
            inputStream = new ByteArrayInputStream(output.toByteArray());
            output.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {

            try {
                if (output != null) {
                    output.close();
                }
                if (inputStream != null) {
                    inputStream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return inputStream;
    }

    @Override
    public boolean yaomaExist(ProjectParam param){
        QueryWrapper<Project> q=new QueryWrapper<>();
        q.eq("yaoma",param.getYaoma());
        if(ToolUtil.isNotEmpty(param.getId())){
            q.ne("id",param.getId());
        }
        List<Project> list = projectMapper.selectList(q);
        return list.size()>0?true:false;

    }

    @Override
    public List<TaskStatus> listgcsToStop(ProjectParam param){
        return projectMapper.listgcsToStop(param);
    }

    @Override
    public List<Integer> findBusinessShopIdsList() {
        List<Integer> shopIds=projectMapper.findBusinessShopIdsList();

        return shopIds;
    }

    @Override
    public List<Map<String, Object>> findBusinessShopList(ProDataViewParam param) {
        List<Map<String, Object>> data=new ArrayList<>();
        if(CollectionUtil.isNotEmpty(param.getParamList())){
           data=projectMapper.findBusinessShopInfoMapList(param);
        }
        return data;
    }

    @Override
    public List<ProjectResult> h5List(ProjectParam param) {
        return projectMapper.h5List(param);
    }

    @Override
    public Page<ProjectResult> h5Lists(ProjectParam param) {
        Page page = getPageContext();
        return projectMapper.h5Lists(page,param);
    }



    @Override
    public Integer gcbFinish(ProjectParam param) {
        return projectMapper.gcbFinish(param);
    }
    @Override
    public Integer ddFinish(ProjectParam param) {
        return projectMapper.ddFinish(param);
    }

    @Override
    public LayuiPageInfo h5Listss(ProjectParam param,HttpServletRequest request) throws ParseException {

        String phones = request.getParameter("phone");
        //获取用户角色
        User user = userService.getAccount(phones);
        List<Long> roleList = new ArrayList<>();
        Long userId=null;
        if (ToolUtil.isNotEmpty(user)) {
            userId = user.getUserId();
            String[] roles = user.getRoleId().split(",");
            for (String role : roles) {
                roleList.add(Long.valueOf(role));
            }
        }
        Map<String, Object> map = new HashMap<>();
        Integer count=null;


        List<Integer> taskByRole = taskStatusService.getTaskByRole(roleList);
        param.setTaskids(StringUtils.join(taskByRole,","));
        User curtuser = userService.getById(userId);
        String phone = curtuser.getPhone();
        String jiedian=param.getJiedian();

        Page pageContext = getPageContext();
        Long role_gczj = RoleIdEnum.ROLE_GCZJ.getCode();//工程总监
        Long role_kfzj = RoleIdEnum.ROLE_KFZJ.getCode();//开发总监
        Long role_yyzj = RoleIdEnum.ROLE_YYZJ.getCode();//营运总监
        Long role_kfry = RoleIdEnum.ROLE_KFRY.getCode();//开发人员
        Long role_yyjl = RoleIdEnum.ROLE_YYJL.getCode();//营运经理
        Long role_dd = RoleIdEnum.ROLE_DD.getCode();//督导
        Long role_netshop = RoleIdEnum.ROLE_NETSHOP.getCode();//网上建店负责人
        Long role_gcb = RoleIdEnum.ROLE_GCB.getCode();//工程部
        if (roleList.contains(role_kfry)) {
            param.setCreateUser(userId);
        }
        if (roleList.contains(role_yyjl)) {
            param.setYyjl(phone);
        }
        if (roleList.contains(role_dd)) {
            param.setDd(phone);
        }
        if(ToolUtil.isNotEmpty(jiedian)){
            param.setJiedian(jiedian);
        }
        IPage page = this.baseMapper.customPageList(pageContext, param);
        taskService.setProcessSteps(page.getRecords());
        List<ProjectResult> records = page.getRecords();

        List<TaskResult> listIds = taskService.listIdsByRoleIds(String.join(",", role_kfry.toString(), role_gczj.toString(), role_kfzj.toString()));
        Map<Long, String> roleIdTaskIds = listIds.stream().collect(Collectors.toMap(TaskResult::getRoleId, TaskResult::getIds));
        //获取开发人员任务完成情况
        String kf_taskids = roleIdTaskIds.get(role_kfry);
        String gczj_taskids = roleIdTaskIds.get(role_gczj);
        String kfzj_taskids = roleIdTaskIds.get(role_kfzj);

        //所有taskStatus信息
        List<TaskStatus> taskStatusList = taskStatusService.listTaskStatus();
        Map<Integer, List<TaskStatus>> taskStatusProIdMap = taskStatusList.stream().collect(Collectors.groupingBy(TaskStatus::getProId));
        List<TaskStatus> rejects = taskStatusService.listReject();
        Map<String, TaskStatus> rejectMap = rejects.stream().collect(Collectors.toMap(k -> k.getProId() + "_" + k.getTaskId(), Function.identity()));
        Date curtDate = new Date();
        List<Map> maps = teamService.selectYyjlList();
        Map<Object, Object> yyjlmap = maps.stream().collect(Collectors.toMap(s -> s.get("tel"), s -> s.get("yyjl")));
        List<Map> maps2 = teamService.selectDdListAll();
        Map<Object, Object> ddmap = maps2.stream().collect(Collectors.toMap(s -> s.get("tel"), s -> s.get("dd")));
        Iterator<ProjectResult> iterator = records.iterator();
        while (iterator.hasNext()) {
            ProjectResult rs = iterator.next();
            Integer proid = rs.getId();

            Map<String, String> openidMap = projectService.selectDd(proid);
            if (ToolUtil.isNotEmpty(openidMap)) {
                rs.setYyjlname(openidMap.get("yyName"));
                rs.setDdname(openidMap.get("ddName"));
            }
            List<TaskStatus> listStatus = taskStatusService.list(new QueryWrapper<TaskStatus>().eq("pro_id", proid)
                    .eq("task_id", 6).ne("status", 0));
            if (listStatus.size() > 0) {
                rs.setSwtj("已填");
            } else {
                rs.setSwtj("");
            }
            List<TaskStatus> listStatuss = taskStatusService.list(new QueryWrapper<TaskStatus>().eq("pro_id", proid)
                    .eq("task_id", 5).ne("status", 0));
            if (listStatuss.size() > 0) {
                rs.setGctj("已填");
            } else {
                rs.setGctj("");
            }

            //获取营运经理完成情况
            String allotDd = rs.getAllotDd();
            if (ToolUtil.isNotEmpty(allotDd) && allotDd.equals("已指定督导")) {
                rs.setYyjlFinish(true);
            }

            //根据角色获取任务ids
            boolean kfry_ts = isexist2(taskStatusProIdMap.get(proid), kf_taskids);
            //获取工程总监任务完成情况
            boolean gczj_ts = isexist2(taskStatusProIdMap.get(proid), gczj_taskids);
            //获取开发总监任务完成情况
            boolean kfzj_ts = isexist2(taskStatusProIdMap.get(proid), kfzj_taskids);
            //获取营运总监审核
            boolean yyzj_ts = isexist2(taskStatusProIdMap.get(proid), "7");
            if (yyzj_ts) {//yyzj已确认
                //是否确认开工日期
                rs.setKgtime("开工日期未确定");
                String kaigong = "32";
//                boolean kaigong_ts = isexist(proid, kaigong);
                List<TaskStatus> listts = this.getTaskStatusListByTaskIds(taskStatusProIdMap.get(proid), kaigong);
                rs.setGckg(enable);
                if (ToolUtil.isNotEmpty(listts)) {
                    long num = DateUtil.getDaysNum(listts.get(0).getContent(), DateUtil.getNowDate());
                    if (num < 0) {
                        rs.setKgtime("开工日期：" + listts.get(0).getContent());
                    } else {
                        //判断工程是否完成
                        List<TaskStatus> list=getTaskStatusListByTaskIds(taskStatusProIdMap.get(proid),"34");
                        if(list.size()>0){
                            String finiDate = list.get(0).getContent();
                            if (ToolUtil.isNotEmpty(finiDate)) {
                                Date finDate = DateUtil.getDateByStr(finiDate);
                                if(finDate.before(curtDate)){
                                    rs.setKgtime("已完工");
                                }else{
                                    rs.setKgtime("已开工" + num + "天");
                                }
                            } else {
                                rs.setKgtime("");
                            }
                        }else{
                            rs.setKgtime("已开工" + num + "天");
                        }
                    }
                }
                if (roleList.contains(role_yyzj)) {//营运总监
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    rs.setSelectyyjl(enable);

                    if (ToolUtil.isNotEmpty(rs.getYyjl())) {
                        /*Map<String, Object> map = new HashMap<>();
                        map.put("tel", rs.getYyjl());
                        BtyArchives arch = btyArchivesMapper.getObjByCon(map);
                        if (arch != null) {
                            rs.setYyjlname(arch.getXm());
                        } else {
                            rs.setYyjlname("无名");
                        }*/
                        rs.setYyjlname(String.valueOf(yyjlmap.get(rs.getYyjl())==null?"无名":yyjlmap.get(rs.getYyjl())));
                    }
                    if (ToolUtil.isNotEmpty(listts) && ToolUtil.isNotEmpty(rs.getDd())) {
                        rs.setKdtask(enable);//开店任务
                    }
                }
                if (roleList.contains(role_yyjl)) {//营运经理
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    rs.setSelectdd(enable);
                    if (ToolUtil.isNotEmpty(rs.getDd())) {
                        /*Map<String, Object> map = new HashMap<>();
                        map.put("tel", rs.getDd());
                        BtyArchives arch = btyArchivesMapper.getObjByCon(map);
                        if (arch != null) {
                            rs.setDdname(arch.getXm());
                        } else {
                            rs.setDdname("无名");
                        }*/
                        rs.setDdname(String.valueOf(ddmap.get(rs.getDd())==null?"无名":ddmap.get(rs.getDd())));
                    }
                    if (ToolUtil.isNotEmpty(listts) && ToolUtil.isNotEmpty(rs.getDd())) {
                        rs.setKdtask(enable);//开店任务
                    }
                }
                if (roleList.contains(role_dd)) {//督导

                    //获取督导任务是否完成
                    ProjectParam projectParam = new ProjectParam();
                    projectParam.setId(proid);
                    Integer ddCount = projectService.ddFinish(projectParam);
                    if (ddCount > 0) {
                        rs.setDdFinish(true);
                    }
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    if (ToolUtil.isNotEmpty(listts) && ToolUtil.isNotEmpty(phone) && phone.equals(rs.getDd())) {
                        rs.setKdtask(enable);//开店任务
                        rs.setKdtaskedit(enable);//开店任务信息可否编辑
                    }
                }
                if (roleList.contains(role_kfry)) {//工程开发人员、
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                }
                if (roleList.contains(role_gczj)) {//工程总监
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                }

                if (roleList.contains(role_gcb)) {//工程部
                    rs.setGcbtn(enable);
                    rs.setGckgedit(enable);
                }
                if (roleList.contains(role_netshop)) {//网上建店负责人
                    if (ToolUtil.isNotEmpty(listts)) {
                        rs.setKdtask(enable);//开店任务
//                        rs.setKdtaskedit(enable);//开店任务信息可否编辑
                    }
                    //如果督导三个表格已完成，才能建店
                    Integer addrMouldid = 34;
                    Integer mealMouldid = 35;
                    Integer queuMouldid = 37;
                    List<MouldBoardMsg> addrlist = mouldBoardMsgMapper.getRecordByMould(addrMouldid);
                    List<MouldBoardMsg> meallist = mouldBoardMsgMapper.getRecordByMould(mealMouldid);
                    List<MouldBoardMsg> queuelist = mouldBoardMsgMapper.getRecordByMould(queuMouldid);
                    if (addrlist.size() > 0) {
                        //网上建店按钮
                        rs.setNetshopAddr(enable);
                    }
                    if (meallist.size() > 0) {
                        //线上套餐按钮
                        rs.setMealOnline(enable);
                    }
                    if (queuelist.size() > 0) {
                        //排队机按钮
                        rs.setQueueMachine(enable);
                    }
                }
                if (roleList.contains(role_kfzj)) {//开发总监
                    //商务条件按钮
                    rs.setSwbtn(enable);
                    //工程条件按钮
                    rs.setGcbtn(enable);
                }
            } else if (gczj_ts && kfzj_ts) {//kfzj+gczj OK
                if (roleList.contains(role_gczj) || roleList.contains(role_kfry)) {//工程总监/开发人员
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                } else if (roleList.contains(role_yyzj)) {//营运总监
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    boolean isexist = isexist2(taskStatusProIdMap.get(proid), "7");//营运总监确认taskid
                    if (!isexist) {
                        //商务条件审核按钮
                        rs.setAuditbtn(enable);
                    }
                } else if (roleList.contains(role_kfzj)) {//开发总监
                    rs.setSwbtn(enable);
                    rs.setGcbtn(enable);
                }
            } else if (kfry_ts) {//开发人员任务完成
                if (roleList.contains(role_gczj)) {//工程总监
                    boolean isexist0 = isexist2(taskStatusProIdMap.get(proid), "6");//开发总监确认
                    if(isexist0){
                        rs.setSwbtn(enable);
                    }else{
                        rs.setSwbtn(2);
                    }
                    rs.setGcbtn(enable);
                    boolean isexist = isexist2(taskStatusProIdMap.get(proid), "5");//工程总监确认taskid
                    if (!isexist) {
                        //商务条件通过驳回按钮是否显示
                        rs.setAuditbtn(disable);
                        //工程条件通过驳回按钮是否显示
                        rs.setAuditbtn1(enable);
                    }
                } else if (roleList.contains(role_kfzj)) {//开发总监
                    rs.setSwbtn(enable);
                    rs.setGcbtn(enable);
                    boolean isexist = isexist2(taskStatusProIdMap.get(proid), "6");//开发总监确认taskid
                    if (!isexist) {
                        //商务条件通过驳回按钮是否显示
                        rs.setAuditbtn(enable);
                        //工程条件通过驳回按钮是否显示
                        rs.setAuditbtn1(disable);
                    }
                } else if (roleList.contains(role_kfry)) {//开发人员
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                } else if (roleList.contains(role_yyzj)) {//营运总监
                    rs.setSwbtn(enable);
                    rs.setGcbtn(enable);
                }
            } else {//kf人员未完成
                boolean swisexist = isexist2(taskStatusProIdMap.get(proid), "3");//sw
                boolean gcisexist = isexist2(taskStatusProIdMap.get(proid), "2");//gc
                if (roleList.contains(role_kfry)) {//开发人员
                    rs.setGcbtn(enable);
                    rs.setSwbtn(enable);
                    if (!swisexist) {
                        //商务模板条件可否编辑
                        rs.setSwedit(enable);
                    }
                    if (!gcisexist) {
                        //工程模板条件可否编辑
                        rs.setGcedit(enable);
                    }
                } else if (roleList.contains(role_kfzj)) {//开发总监
                    if (swisexist) {//店名和商务条件完成
                        rs.setSwbtn(enable);
                        boolean isexist = isexist2(taskStatusProIdMap.get(proid), "6");//开发总监确认taskid
                        if (!isexist) {
                            //商务条件通过驳回按钮是否显示
                            rs.setAuditbtn(enable);
                        }
                    }
                    if (gcisexist) {
                        rs.setGcbtn(enable);
                    }
                } else if (roleList.contains(role_yyzj)) {//营运总监
                    if (swisexist) {
                        rs.setSwbtn(enable);
                    }
                    if (gcisexist) {
                        rs.setGcbtn(enable);
                    }
                }
                if(ToolUtil.isNotEmpty(rs.getKfzj()) && rs.getKfzj().contains("驳回")){
                    rs.setSwbtn(-1);
                    TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_6.getCode());
                    rs.setRejectInfo("开发总监'"+rej.getCreateName()+"'已驳回,原因："+rej.getContent());
                }
                if(ToolUtil.isNotEmpty(rs.getGczj()) && rs.getGczj().contains("驳回")){
                    rs.setGcbtn(-1);
                    TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_5.getCode());
                    rs.setRejectInfo("工程总监'"+rej.getCreateName()+"'已驳回,原因："+rej.getContent());
                }
                if(ToolUtil.isNotEmpty(rs.getYyzj()) && rs.getYyzj().contains("驳回")){
                    rs.setGcbtn(-1);
                    TaskStatus rej = rejectMap.get(proid + "_" + ProjectTaskEnum.TASK_7.getCode());
                    rs.setRejectInfo("营运总监'"+rej.getCreateName()+"'已驳回,原因："+rej.getContent());
                }
            }

        }
        List<ProjectResult> listKfry = new ArrayList<>();
        List<ProjectResult> listKfzj = new ArrayList<>();
        List<ProjectResult> listGczj = new ArrayList<>();
        List<ProjectResult> listYyzj = new ArrayList<>();
        List<ProjectResult> listGcb = new ArrayList<>();
        List<ProjectResult> listDd = new ArrayList<>();
        List<ProjectResult> listYyjl = new ArrayList<>();


        // 同时包含"营运经理","工程部","工程开发人员" 这三个角色的已完成列表
        if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_kfry) && roleList.contains(role_yyjl) && roleList.contains(role_gcb)) {
            for (ProjectResult record : records) {
                if (record.getKfryFinish().equals(true)) {
                    listKfry.add(record);
                }
                if (record.getYyjlFinish().equals(true)) {
                    listKfry.add(record);
                }
                if (record.getGcbFinish().equals(true)) {
                    listKfry.add(record);
                }
            }
            count = listKfry.size();
            page.setTotal(count);
            page.setRecords(listKfry);
        }
        // 同时包含"营运经理","工程部","工程开发人员" 这三个角色的未完成列表
        else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_kfry) && roleList.contains(role_yyjl) && roleList.contains(role_gcb)) {
            for (ProjectResult record : records) {
                if (record.getKfryFinish().equals(false)) {
                    listKfry.add(record);
                }
                if (record.getYyjlFinish().equals(false)) {
                    listKfry.add(record);
                }
                if (record.getGcbFinish().equals(false)) {
                    listKfry.add(record);
                }
            }
            count = listKfry.size();
            page.setTotal(count);
            page.setRecords(listKfry);
        }

        // 同时包含"营运经理","工程开发人员" 这两个角色的已完成列表
        else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_kfry) && roleList.contains(role_yyjl)) {
            for (ProjectResult record : records) {
                if (record.getKfryFinish().equals(true)) {
                    listKfry.add(record);
                }
                if (record.getYyjlFinish().equals(true)) {
                    listKfry.add(record);
                }
            }
            count = listKfry.size();
            page.setTotal(count);
            page.setRecords(listKfry);
        }
        // 同时包含"营运经理","工程开发人员" 这两个角色的未完成列表
        else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_kfry) && roleList.contains(role_yyjl)) {
            for (ProjectResult record : records) {
                if (record.getKfryFinish().equals(false)) {
                    listKfry.add(record);
                }
                if (record.getYyjlFinish().equals(false)) {
                    listKfry.add(record);
                }
            }
            count = listKfry.size();
            page.setTotal(count);
            page.setRecords(listKfry);
        }

        // 同时包含"督导","工程开发人员" 这两个角色的已完成列表
        else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_kfry) && roleList.contains(role_dd)) {
            for (ProjectResult record : records) {
                if (record.getKfryFinish().equals(true)) {
                    listKfry.add(record);
                }
                if (record.getDdFinish().equals(true)) {
                    listKfry.add(record);
                }
            }
            count = listKfry.size();
            page.setTotal(count);
            page.setRecords(listKfry);
        }
        // 同时包含"督导","工程开发人员" 这两个角色的未完成列表
        else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_kfry) && roleList.contains(role_dd)) {
            for (ProjectResult record : records) {
                if (record.getKfryFinish().equals(false)) {
                    listKfry.add(record);
                }
                if (record.getDdFinish().equals(false)) {
                    listKfry.add(record);
                }
            }
            count = listKfry.size();
            page.setTotal(count);
            page.setRecords(listKfry);
        }

        //开发人员已完成列表
        else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_kfry)) {
            for (ProjectResult record : records) {
                if (record.getKfryFinish().equals(true)) {
                    listKfry.add(record);
                }
            }
            count = listKfry.size();
            page.setTotal(count);
            page.setRecords(listKfry);
            //开发人员未完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_kfry)) {
            for (ProjectResult record : records) {
                if (record.getKfryFinish().equals(false)) {
                    listKfry.add(record);
                }
            }
            count = listKfry.size();
            page.setTotal(count);
            page.setRecords(listKfry);
            //开发总监已完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_kfzj)) {
            for (ProjectResult record : records) {
                if (record.getKfzjFinish().equals(true)) {
                    listKfzj.add(record);
                }
            }
            count = listKfzj.size();
            page.setTotal(count);
            page.setRecords(listKfzj);
            //开发总监未完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_kfzj)) {
            for (ProjectResult record : records) {
                if (record.getKfzjFinish().equals(false)) {
                    listKfzj.add(record);
                }
            }
            count = listKfzj.size();
            page.setTotal(count);
            page.setRecords(listKfzj);
            //工程总监已完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_gczj)) {
            for (ProjectResult record : records) {
                if (record.getGczjFinish().equals(true)) {
                    listGczj.add(record);
                }
            }
            count = listGczj.size();
            page.setTotal(count);
            page.setRecords(listGczj);
            //工程总监未完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_gczj)) {
            for (ProjectResult record : records) {
                if (record.getGczjFinish().equals(false)) {
                    listGczj.add(record);
                }
            }
            count = listGczj.size();
            page.setTotal(count);
            page.setRecords(listGczj);
            //营运总监已完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_yyzj)) {
            for (ProjectResult record : records) {
                if (record.getYyzjFinish().equals(true)) {
                    listYyzj.add(record);
                }
            }
            count = listYyzj.size();
            page.setTotal(count);
            page.setRecords(listYyzj);
            //营运总监未完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_yyzj)) {
            for (ProjectResult record : records) {
                if (record.getYyzjFinish().equals(false)) {
                    listYyzj.add(record);
                }
            }
            count = listYyzj.size();
            page.setTotal(count);
            page.setRecords(listYyzj);
            //工程部已完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_gcb)) {
            for (ProjectResult record : records) {
                if (record.getGcbFinish().equals(true)) {
                    listGcb.add(record);
                }
            }
            count = listGcb.size();
            page.setTotal(count);
            page.setRecords(listGcb);
            //工程部未完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_gcb)) {
            for (ProjectResult record : records) {
                if (record.getGcbFinish().equals(false)) {
                    listGcb.add(record);
                }
            }
            count = listGcb.size();
            page.setTotal(count);
            page.setRecords(listGcb);
        }
        //督导已完成列表
        else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_dd)) {
            for (ProjectResult record : records) {
                if (record.getDdFinish().equals(true)) {
                    listDd.add(record);
                }
            }
            count = listDd.size();
            page.setTotal(count);
            page.setRecords(listDd);
            //督导未完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_dd)) {
            for (ProjectResult record : records) {
                if (record.getDdFinish().equals(false)) {
                    listDd.add(record);
                }
            }
            count = listDd.size();
            page.setTotal(count);
            page.setRecords(listDd);
        }
        //营运经理已完成列表
        else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("Y") && roleList.contains(role_yyjl)) {
            for (ProjectResult record : records) {
                if (record.getYyjlFinish().equals(true)) {
                    listYyjl.add(record);
                }
            }
            count = listYyjl.size();
            page.setTotal(count);
            page.setRecords(listYyjl);
            //营运经理未完成列表
        } else if (ToolUtil.isNotEmpty(param.getIsFinish()) && param.getIsFinish().equals("N") && roleList.contains(role_yyjl)) {
            for (ProjectResult record : records) {
                if (record.getYyjlFinish().equals(false)) {
                    listYyjl.add(record);
                }
            }

            count = listYyjl.size();
            page.setTotal(count);
            page.setRecords(listYyjl);
//            map.put("list",listYyjl);
//            map.put("count", count);
        } else {
//            map.put("list", records);
//            map.put("count", records.size());

            page.setTotal(records.size());
            page.setRecords(records);
            //return ResponseData.success(map);
        }
        System.out.println("page:"+page);
        return LayuiPageFactory.createPageInfo(page);
    }


    @Override
    public LayuiPageInfo projectWjcList(ProjectParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.projectWjcList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public Object wjcList() {
        return this.baseMapper.wjcList();
    }

    @Override
    public List<Project> projectCloseList() {
        return baseMapper.projectCloseList();
    }

    /**
     * 确认店名列表
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo confirmList(ProjectParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.confirmList(pageContext, param);
        //获取该店营业额
        List<Map> list = baseMapper.getYye(param);

        List<Map<String,Object>> mapList = page.getRecords();
        for(Map<String,Object> map : mapList){

            if (ToolUtil.isNotEmpty(list)){
                Map<Object, Object> yyeMap = list.stream().collect(Collectors.toMap(s -> s.get("id"), s -> s.get("yye")));
                if (ToolUtil.isEmpty(yyeMap)){
                    map.put("yye", 0);
                }else {
                    map.put("yye", yyeMap.get(map.get("id")));
                }
            }
        }

        return LayuiPageFactory.createPageInfo(page);
    }

    /**
     * 收银建店列表
     * @param param
     * @return
     */
    @Override
    public LayuiPageInfo syShopList(ProjectParam param) {
        Page pageContext = getPageContext();
        //已确认店名的店
        IPage page = this.baseMapper.syShopList(pageContext, param);

        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public List<Map> qyjlList() {
        return baseMapper.qyjlList();
    }

}
